Does "for of" loop in javascript stop until receiving value from "await" on every iteration?

Viewed 29

In this article https://riptutorial.com/javascript/example/7746/looping-with-async-await I read that we wait on every iteration of "for of" loop, but after I checked it in codesandox I realized that all the promises start being executed simultaniously, so the loop doesnt stop on every iteration, but the code inside every iteration stops. Does this article have incorrect info?


Screenshot from article - enter image description here


My code

const promises = [];

for (let i = 1; i < 4; i++) {
  promises.push(
    new Promise((res, _) => {
      setTimeout(async () => {
        res(i);
      }, 2000);
    })
  );
}

(async () => {
  for (let promise of promises) {
    const r = await promise;
    console.log(r);
  }
})();

1 Answers

When you create a new Promise, the internal function of that promise runs as soon as it gets the opportunity to.

Instead, you could do something like this to make the internal function wait until it's called from your second loop:

const promiseFuncs = [];

for (let i = 1; i < 4; i++) {
  promiseFuncs.push(
    () => new Promise((res, _) => {
      setTimeout(async () => {
        res(i);
      }, 2000);
    })
  );
}

(async () => {
  for (let promiseF of promiseFuncs) {
    const r = await promiseF();
    console.log(r);
  }
})();

Related