循环Node.js的异步
我正在尝试使循环在console.log
之前运行,但首先运行的是console.log
for(let i = 0; i < 10; i++){
setTimeout(function(){
console.log("hello " + i);
}, 500);
}
console.log("Bye bye");
回答如下:因为javascript中的大多数函数都是异步的(最著名的是Promises
,setTimeout
和setInterval
),以避免阻塞流执行,所以循环不会等待setTimeout
函数继续执行。] >
您可以使用async/await
函数执行类似的操作,该函数将在继续执行之前等待解决承诺,请谨慎使用the setTimeout in loop(不建议这样做)
如果要实现这一点,可以执行以下操作:
;(async () => { // Declaration to make the code async
for(let i = 0; i < 10; i++){
await new Promise(resolve => setTimeout(function(){
console.log("hello " + i);
resolve();
}, 500));
}
console.log("Bye bye");
})();