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

96 thoughts on “How to fix async code inside loop to run program in sequence”

Leave a Comment