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

Time:09-21

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

CodePudding user response:

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 ]

CodePudding user response:

I think you forgot the "await" before calling your work() function.

  • Related