[英]How to fix async code inside loop to run program in sequence
控制台下的代码日志为假,但我希望它为真如何使异步代码首先运行并在循环后使用迭代值
const arr = [1, 2, 1, 2, 1, 2, 1]; let total = 0; for (let a of arr) { setTimeout(() => { if (a === 1) { total++; } }, 1000); } if (total === 4) { console.log('true'); } else { console.log('false'); }
因为setTimeout()
是异步且非阻塞的,所以你的for
循环只是设置了一堆计时器,然后在任何计时器触发之前立即运行检查total
的代码,因此在任何计时器增加total
之前。
要修复,您可以将超时更改为 promise 并使用async
和await
按顺序运行循环:
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
async function run() {
const arr = [1, 2, 1, 2, 1, 2, 1];
let total = 0;
for (let a of arr) {
await delay(1000);
if (a === 1) {
total++;
}
}
if (total === 4) {
console.log('true');
} else {
console.log('false');
}
}
run();
或者,并行运行所有计时器:
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
async function run() {
const arr = [1, 2, 1, 2, 1, 2, 1];
let total = 0;
await Promise.all(arr.map(a => {
return delay(1000).then(() => {
if (a === 1) total++;
});
}));
if (total === 4) {
console.log('true');
} else {
console.log('false');
}
}
run();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.