我在理解 NodeJS 上代码执行的异步特性时遇到了很多麻烦。我有一个简单的函数可以在 Linux 机器上获取 ip a 的输出并手动解析出 IP 子网。完成后我只想 console.log()
IP 子网。
我知道 NodeJS 主要是异步运行的,所以我不能期望逻辑在我 console.log()
变量之前完成。我理解回调的概念来解决这个问题,但我更喜欢访问逻辑循环之外的变量。我转向 Promises,这似乎是一个很好的解决方案,但我认为我错过了一些东西,而且它们没有按照我预期的方式工作。下面是我的代码:
let subnetString = '';
function getIPLinux() {
return new Promise((resolve) => {
const ipOutput = spawn( 'ip', ['a'] );
ipOutput.stdout.on('data', (data) => {
String(data).split('\n').forEach( (line) => {
if ( line.includes('inet') && line.indexOf('inet6') < 0 && line.indexOf('127.0.0.1') < 0 ) {
const ipSubnet = line.split(' ')[5];
const ipStringArray = ipSubnet.split('.');
subnetString = ipStringArray[0] + '.' + ipStringArray[1] + '.' + ipStringArray[2] + '.*';
console.log('Found subnet at end of if loop: ' + subnetString);
}
})
})
console.log('Found subnet at end of promise: ' + subnetString);
resolve();
})
}
getIPLinux().then( () => {
console.log('Found subnet after then: ' + subnetString);
});
我的输出如下:
Found subnet at end of promise:
Found subnet after then:
Found subnet at end of if loop: 192.168.1.*
只有最后一行记录是正确的。我很难理解这种非阻塞代码执行。如果我的方法是错误的,我也愿意接受其他方法。
最佳答案
spawn() 也是异步的。您正在为标准输出使用事件回调,这很好,但您正在立即解决下面的 promise ,而无需等待输入完成。尝试一下
ipOutput.on('close', () => {
console.log('Found subnet at end of promise: ' + subnetString);
resolve(subnetString);
});
在你的 promise 结束时。
https://nodejs.org/api/child_process.html#child_process_event_close
关于node.js - NodeJS 中的 Promise 困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54853080/