Javascript - trying to understand how promises work when using loop

33 Views Asked by At

In this example, the order of res is preserved, because await is used within a for loop, which processes each promise sequentially. This means the loop waits for the current promise to resolve before moving to the next iteration.

async function processPromises(promises) {
    const res = [];
    for (let i = 0; i < promises.length; i++) {
        const val = await promises[i];
        res.push(val);
    }
    return res;
}

so you will have

res = [resolve1st, resolve2nd, resolve3rd, ...]

Now for below example

  const res = [];
  promises.forEach(async (_, i) => {
        const val = await promises[i];
        res.push(val);
  });
  return res;

The value of res is unpredictable. I know we can actually use Promise.all in this case, but I am eager to know how it works.

My guess is that, for each iteration in forEach, it runs asychronously. The promises are not required to resolve immediately before moving to the next iteration. After all iteration of promises, return res; runs before all promises resolved(some of them are still in task queue waiting to be moved to the call stack).

If that's the case, I still can't explain to myself, how The promises are not required to resolve immediately before moving to the next iteration. Maybe I am wrong?

0

There are 0 best solutions below