【发布时间】:2020-05-15 09:15:09
【问题描述】:
为什么代码会这样打印??
循环下不能使用await吗?
>>>>> START
1
预期结果是'>>>>> START 1 2 3 >>>>> END'
let arr = [1, 2, 3]
async function print() {
for (let n of arr) {
await new Promise(
resolve => {
setTimeout(() => {
console.log(n);
resolve;
}, 1000)
}
);
}
}
async function main() {
console.log(">>>>> START");
await print();
console.log(">>>>> END");
}
main()
【问题讨论】:
-
试试这个
setTimeout(() => { console.log(n); resolve(); }, 1000) -
因为第一个承诺没有解决,所以你的代码等到第一个承诺得到解决
标签: node.js for-loop asynchronous async-await