Home > Software engineering >  Does "for of" loop in javascript stop until receiving value from "await" on ever
Does "for of" loop in javascript stop until receiving value from "await" on ever

Time:09-15

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

CodePudding user response:

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