0

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');
}

3
  • 2
    loop is your enemy in async node. Use map instead to transform it into a list of Promises and then use Promise.all(your_promise_collection).then(). Note that your setTimeout logic isn't a promise Commented Jan 28, 2021 at 7:45
  • can you tell me where did i go wrong here?? Commented Jan 28, 2021 at 8:02
  • 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(result) if (total === 4) { console.log('true'); } else { console.log('false'); } }) Commented Jan 28, 2021 at 8:03

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.