DEV Community

Discussion on: Don't await in loops

Collapse
 
jalal246 profile image
Jalal 🚀 • Edited

async function doesn't work inside for loop

for (let i = 0; i < array.length; i++) {
  // it won't wait here. 
  const result = await work(array[i]);

  // result is an unresolved promise.
  doSomething(result);
}

Instead, you push all promises in an array then resolve them with Promise.all

Collapse
 
karataev profile image
Eugene Karataev

Actually, async works as expected in for loop.

function work(n) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(n * 10);
    }, 200);
  })
}

(async function() {
  array = [1,2,3];
    for (let i = 0; i < array.length; i++) {
    // it WILL wait here. 
    const result = await work(array[i]);

    // result is 10, 20, 30 as expected
    console.log(result);
  }
})();
Collapse
 
arnaud profile image
Arnaud

Yes, that's exactly it!