我正在研究 mikrotik 路由器的 router-os 库。 我在回调之外显示对 API 的调用时遇到问题。 foo 变量应该包含 API 中的对象恢复,只是我无法解决异步问题
var MikroNode = require('mikronode-ng2');
const USER = "sofian";
const PASSWD = "sofian"
var toto;
var connection = MikroNode.getConnection('10.0.0.1', USER, PASSWD)
connection.connect(function (conn) {
var chan = conn.openChannel();
conn.closeOnDone = true;
chan.write('/ip/address/print', function () {
chan.closeOnDone = true;
chan.on('done', function (data) {
var parsed = MikroNode.parseItems(data);
toto = parsed
parsed.forEach(function (item) {
console.log('Interface/IP: ' + item.interface + "/" + item.address);
})
})
})
})
console.log(toto);
返回终端:
undefined
Interface/IP: Lan/10.0.0.1/8
Interface/IP: Wan Orange/192.168.1.254/24
谢谢
用 promise 编辑:
我尝试了一下,还是不行
var MikroNode = require('mikronode-ng2');
const USER = "sofian";
const PASSWD = "sofian"
var connection = MikroNode.getConnection('10.0.0.1', USER, PASSWD)
var result;
function test() {
connection.getConnectPromise().then( function (conn) {
conn.getCommandPromise('/ip/address/print').then(async function resolved(values) {
// console.log('Addreses: ' + JSON.stringify(values));
result = 'Addreses: ' + JSON.stringify(values)
return await result;
})
})
}
console.log(test())
终端:
undefined
我添加了 async/await 但它没有解决我的问题
最佳答案
您无法将异步数据(例如数据
、解析
等)拉入同步上下文。想一想:通过将回调传递给 connection.connect()
,您可以告诉它“在将来某个不确定的时间,当您完成连接时调用此函数”,然后代码立即继续,并在回调执行之前相对较早地命中 console.log(toto)
。在该回调中创建的数据无法及时返回。
如果您想像同步一样编写异步代码,请使用 async/await - 您正在使用的库 does seem to support promises ,因此您必须使用这些函数来这样做。
关于javascript - 保存nodejs的回调返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58848457/