[英]Node.js: How to prevent the next line execution until my forLoop gives me result
let a = []
for (let i=0;i<4;i++){
setTimeout(()=>{
a.push(i);
},2000)
}
console.log(a);
Here I am getting a always blank [].在这里,我得到一个始终空白的 []。 Please suggest a way to stop executing console.log(a) line until a gets filled.
请提出一种方法来停止执行 console.log(a) 行,直到 a 被填满。
You should await setTimeout
:你应该等待
setTimeout
:
let a = [];
async function test() {
for (let i = 0; i < 4; i++) {
await new Promise((resolve) =>
setTimeout(() => {
a.push(i);
resolve();
}, 2000)
);
}
}
await test();
console.log(a);
Note: You can also use Promise.allSettled
to run them at the same time注意:也可以使用
Promise.allSettled
来同时运行它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.