Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading