Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
Promise.race() multiple resolved promises

The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.

Taken from MDN site.

I have 5 promises and I need to know once any 2 promises are resolved, taking performance under consideration.

const sleep = ms =>
  new Promise(r => setTimeout(r, ms))

async function swimmer (name) {
  const start = Date.now()
  console.log(`${name} started the race`)
  await sleep(Math.random() * 5000)
  console.log(`${name} finished the race`)
  return { name, delta: Date.now() - start }
}

const swimmers =
  [ swimmer("Alice"), swimmer("Bob"), swimmer("Claire"), swimmer("David"), swimmer("Ed") ];

Promise.race(swimmers)
  .then(({ name }) => console.log(`*** ${name} is the winner!!! ***`))
  .catch(console.error)

This will return the fastest swimmer but I would like to print once I get 2 promises resolved.

How can I do it?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could write a custom implementation of Promise.race that returns a promise that is resolved with the result of 2 promises that are resolved before others.

Following code example shows an implementation:

function customPromiseRace(promiseArr, expectedCount) {
   return new Promise((resolve, reject) => {
      if (promiseArr.length < expectedCount) {
        throw new Error(`Not enough promises to get ${expectedCount} results`);
      }
      // array to store the results of fulfilled promises
      const results = [];  

      for (const p of promiseArr) {
        Promise.resolve(p).then(result => {
          // push the promise fulfillment value to the "results"
          // array only if we aren't already finished
          if (results.length < expectedCount) {
            results.push(result);
          
            if (results.length === expectedCount) {
              resolve(results);
            }
          }
        }, reject);
      }
   });
}

Demo

const sleep = ms => new Promise(r => setTimeout(r, ms));

async function swimmer(name) {
  const start = Date.now();
  console.log(`${name} started the race`);
  await sleep(Math.random() * 5000);
  console.log(`${name} finished the race`);
  return { name, delta: Date.now() - start };
}

const swimmers = [
  swimmer('Alice'),
  swimmer('Bob'),
  swimmer('Claire'),
  swimmer('David'),
  swimmer('Ed'),
];

function customPromiseRace(promiseArr, expectedCount) {
   return new Promise((resolve, reject) => {
      if (promiseArr.length < expectedCount) {
        throw new Error(`Not enough promises to get ${expectedCount} results`);
      }
      const results = [];  

      for (const p of promiseArr) {
        Promise.resolve(p).then(result => {
          if (results.length < expectedCount) {
            results.push(result);
            if (results.length === expectedCount) {
              resolve(results);
            }
          }
        }, reject);
      }
   });
}

customPromiseRace(swimmers, 2).then(console.log).catch(console.error);

about 4 years ago · Juan Pablo Isaza Report

0

You could use .then(handleMyPromise) inside of Promise.race.

Example:

let handlepromise1 = function ( response ){
    console.log("Expected response: ",response);
    return response;
}

let promise1 = function () {
    return new Promise((r) => {
        setTimeout(()=>{
            console.log("Promise1 says");
            r("promise1")
        },2000)
    })
}

let timeout = function(){
    return new Promise((r) => {
        setTimeout(()=>{
            console.log("timeout says");
            r("timeout")
        },3000)
    });
};

(async function(){
    let func = async function tt(){
        let r = await Promise.race([
            promise1().then(handlepromise1),
            timeout()
        ])

        console.log("Result: ",r);
    }

    func()
})()

Result of console:

Promise1 says
Expected response:  promise1
Result:  promise1
timeout says
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!