Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

javascript - How to fix async code inside loop to run program in sequence

Code below-console log false but I want it to be true How to make an async code run first and use the iterated value after the loop

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');
}
question from:https://stackoverflow.com/questions/65932867/how-to-fix-async-code-inside-loop-to-run-program-in-sequence

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because setTimeout() is asynchronous and non-blocking, your for loop just sets a bunch of timers and then immediately runs the code that checks the total before any of the timers have fired and thus before any of the timers have incremented the total value.

To fix, you can change the timeout to be a promise and use async and await to run the loop sequentially:

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

Or, to run all the timers in parallel:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...