【发布时间】:2020-03-02 05:07:48
【问题描述】:
我正在使用 exec 在 node 中试验 shell 命令,但代码没有按我期望的顺序执行。
这是代码。
const { exec } = require('child_process');
var newDataArray = []
for (var i = 0; i < 10; i++) {
console.log(i)
let printHelloCommand = 'echo hello' + i;
exec(printHelloCommand, (err) => {
if (err) {
console.error(err)
} else {
newDataArray.push(i)
console.log(newDataArray)
console.log("------")
}
})
}
console.log("Printing array")
console.log(newDataArray)
这是我收到的输出。
0
1
2
3
4
5
6
7
8
9
Printing array
[]
[ 10 ]
------
[ 10, 10 ]
------
[ 10, 10, 10 ]
------
[ 10, 10, 10, 10 ]
------
[ 10, 10, 10, 10, 10 ]
------
[ 10, 10, 10, 10, 10, 10 ]
------
[ 10, 10, 10, 10, 10, 10, 10 ]
------
[ 10, 10, 10, 10, 10, 10, 10, 10 ]
------
[ 10, 10, 10, 10, 10, 10, 10, 10, 10 ]
------
[ 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 ]
代码执行无处不在。第 9 行中的 console.log(i) 正在完全打印,但它应该只打印一次循环。然后执行跳到文件末尾以在空数组上打印,并且被推入数组的唯一值是10,即使它应该将i的每个值从1-10推入数组。
我该如何解决这个问题?我尝试了 blue-bird 库中的 promise,但似乎没有解决我的问题。
【问题讨论】:
-
在 JavaScript 中,使用
var声明的成员没有块范围。用let声明的那些确实具有块范围。这应该有助于解释为什么newDataArray完全填充了十位。 -
您需要意识到的另一件事是
for循环同步执行,而(err) => {...}回调异步执行。
标签: node.js asynchronous promise async-await