Skip to content
Advertisement

How to wait for Promise.all() to complete before reaching next line?

I’m learning Node.js.

I have to call an async function work() inside my Promise.all() loop and it must be completed before moving on to statements that are after the Promise.all(). Currently, it reaches the FINISH statment before completing work().

What is the right way to make the code wait for work() function to complete?

const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);

async function work() {
    await new Promise((resolve, reject) => {
        setTimeout(resolve, 2000, 'foo');
    })
    console.log('some work here')
}

async function main() {
    await Promise.all([promise1, promise2, promise3]).then((values) => {
        values.forEach(function(item) {
            console.log(item)
            work()
        });
    });
    console.log('FINISH')
}

main()

Advertisement

Answer

It’s hard to tell what you’re really after here, but don’t mix and match await and then, in general.

const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function work(value) {
  await delay(1000 * value);
  console.log("some work here", value);
  await delay(1000);
  return value * 2;
}

async function main() {
  // Doesn't really do much, since these are already resolved...
  const values = await Promise.all([promise1, promise2, promise3]);
  // Pass all of those values to `work`, which returns a promise,
  // and wait for all of those promises to resolve.
  const workedValues = await Promise.all(values.map(work));
  console.log(workedValues);
}

main();

prints out (the first lines with various delays)

some work here 1
some work here 2
some work here 3
[ 2, 4, 6 ]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement