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

Wait for half of the promises to resolve

I want to parallel process a number of asynchronous calls in NodeJS. I can continue if a specific number of those calls resolve or all of them are completed(some resolve, some reject). How to to do this?

Promise.All() resolves when all of the promises are completed and Promise.Any() resolves when any one of the promise is resolved or all are rejected. Is there any way to wait for 50% of the promises to resolve or n number of promises to resolve instead of waiting for all to resolve.

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

>Solution :

You can write a function that attaches a then callback to each given Promise, incrementing the count each time and resolving once the count reaches a certain value.

A basic example:

function nResolve(promises, n) {
  let count = 0;
  return new Promise((resolve, reject) => {
    promises.forEach(promise => promise.then(() => {
      if (++count >= n) resolve();
    }));
  });
}
const delay = ms => new Promise(r => setTimeout(() => {
  console.log(ms);
  r();
}, ms));
nResolve([delay(100), delay(500), delay(1000), delay(2000), 
  delay(3000), delay(5000), delay(10000)], 4)
  .then(() => console.log('4 Promises resolved'));
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