node.js - NodeJS 中的 Promise 困惑

标签 node.js javascript

我在理解 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/

相关文章:

javascript - 有人可以用更外行的术语解释什么是 util.inherits 吗?

node.js - 维护同一域上托管的多个 Node-Red 实例之间的 session

mysql - node.js + socket.io 聊天应用

javascript - WshShell 无需等待即可运行,但执行状态更新(运行与执行问题)

javascript - 单行 HTML CSS 上的长响应标题

javascript - jQuery 表格行在 Firefox 中无法正确显示

node.js - 我应该在嵌套的 Promise 上调用 .catch 吗?

javascript - 使用 jqueryrateit 插件从星星中获取选定的值

javascript - 如何将 JSONArray 转换为 JsArray?

javascript - 如何获得刷新 token ?