【问题标题】:How to fix async code inside loop to run program in sequence如何修复循环内的异步代码以按顺序运行程序
【发布时间】: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


【解决方案1】:

因为setTimeout() 是异步且非阻塞的,所以您的for 循环只是设置了一堆计时器,然后在任何计时器触发之前立即运行检查total 的代码,因此在任何计时器触发之前计时器增加了total 的值。

要解决此问题,您可以将超时更改为承诺并使用asyncawait 依次运行循环:

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();

【讨论】:

    猜你喜欢
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多