2017-05-09 73 views
0

作爲Node新手,我仍然遇到一些回調問題。我想在函數找到的所有VLAN中循環。一旦它遍歷所有的VLAN,創建地圖,我想將地圖輸出到瀏覽器。但是,我得到的唯一結果是{}。我如何將映射發送到瀏覽器?我甚至不確定我是否正確使用我的回調。Node.js循環回調的問題

var express = require('express'); 
var router = express.Router(); 
var snmp = require('snmp-native'); 


// Create a Session with explicit default host, port, and community. 
let session = new snmp.Session({ host: 'AASW0120', port: 161, community: 'community' }) 

let Mibs = { 
    hostname: [1,3,6,1,2,1,1,5,0], 
    vlans: [1,3,6,1,4,1,9,9,46,1,3,1,1,2], 
    dot1dBasePortIfIndex: [1,3,6,1,2,1,17,1,4,1,2] 
} 


/* Get all VLANs on switch */ 
function vlans(snmpSession, cb) { 
    let vlans = [] 
    session.getSubtree({ oid: Mibs.vlans }, function (error, varbinds) { 
     if (error) { 
      console.log('Fail :('); 
     } else { 
      varbinds.forEach(function (varbind) { 
       vlans.push(varbind.oid[varbind.oid.length -1]) 
      }) 
     } 
     cb(vlans) 
    }) 
} 


/* Map BPIs to Ifindices */ 
function mapBpiIfindex(session, cb) { 
    let map = {} 
    vlans(session, function (vlans) { 
     vlans.forEach(function (vlan) { 
      session.getSubtree({oid: Mibs.dot1dBasePortIfIndex, community: '[email protected]' + vlan}, function (error, varbinds) { 
       if (error) { 
        console.log('Fail :(') 
       } else { 
        varbinds.forEach(function (varbind) { 
         map[varbind.oid[varbind.oid.length -1]] = {ifindex: varbind.value, vlan: vlan} 
        }) 
       } 
      }) 
     }) 
     cb(map) 
    }) 
} 



router.get('/vlans', function (req, res, next) { 
    vlans(session, function (vlans) { 
     res.send(vlans) 
    }) 
}) 

router.get('/bpi-ifindex', function (req, res, next) { 
    mapBpiIfindex(session, function (mapping) { 
     res.send(mapping) 
    }) 
}) 

回答

0

答案是否定的,你不會正確地使用它;) 這裏有幾件事情:

  1. 你應該清楚,只有回調中的代碼運行後執行已完成,因此cb(map)不會等到所有迴環完成。爲什麼不返回任何(因爲當CB被調用時,異步功能還沒有完成,映射值是不確定的多數民衆贊成。看一看這個How do I return the response from an asynchronous call?,它的原理相同。

  2. 看一看async模塊。具體來說如果你介意的性能做*或方法的同時,它會幫你處理與異步函數調用的循環。

  3. 除此之外,你should not use forEach