【发布时间】:2021-05-02 02:20:30
【问题描述】:
控制台日志下方的代码 false 但我希望它是 true 如何让异步代码先运行,循环后使用迭代值
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');
}
【问题讨论】:
-
循环是异步节点中的敌人。改用 map 将其转换为 Promise 列表,然后使用 Promise.all(your_promise_collection).then()。请注意,您的 setTimeout 逻辑不是承诺
-
你能告诉我我哪里出错了吗??
-
const arr = [1, 2, 1, 2, 1, 2, 1] let total = 0 const arrPromises = arr.map(a=>{ return new Promise((res,rej) =>{ setTimeout(() => { `if (a === 1) { total++ res() } }, 1000); }) }) Promise.all(arrPromises).then(result=>{ console.log (结果) if (total === 4) { console.log('true'); } else { console.log('false'); } })
标签: javascript node.js asynchronous promise callback