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.

>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'));

Leave a Reply