2017-05-09 81 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