【问题标题】:Node.js trouble with callback in loopNode.js 循环中的回调问题
【发布时间】:2017-05-09 14:29:40
【问题描述】:

作为 Node 新手,我仍然在回调方面遇到一些问题。

mapBpiIfindex 函数中,我试图循环通过vlans 函数找到的所有VLAN。一旦它遍历了所有 VLAN,创建了地图,我想将地图输出到浏览器。但是,我得到的唯一输出是{}。如何将映射发送到浏览器?我什至不确定我是否正确使用了回调。

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: 'community@' + 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)
    })
})

【问题讨论】:

    标签: node.js express callback snmp


    【解决方案1】:

    答案是否定的,你没有正确使用它;) 这里有几件事:

    1. 您应该清楚在操作完成后执行回调中的代码,因此cb(map)不会等到所有循环的回调完成。这就是为什么什么都不返回的原因(因为调用 cb 时,异步函数尚未完成,映射值未定义。看看这个How do I return the response from an asynchronous call?,原理相同。

    2. 查看async 模块。具体来说,do* 或 while 方法。它将帮助您处理带有异步函数调用的循环。

    3. 除此之外,如果您介意性能,请should not use forEach

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      • 2011-11-08
      • 1970-01-01
      • 2015-11-01
      相关资源
      最近更新 更多