Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
  }
})();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading