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

159
Views
Is there a way to stop the late method when executing Promise.race?

The code below is a just simple example.

function delay(time) {
    return new Promise(function (resolve) {
        setTimeout(resolve, time);
    }).then((e) => {
        console.log(`Wait ${time}ms.`);
        return time;
    });
}

async function main() {
    let r = await Promise.race([
        delay(1000),
        delay(2000),
    ]);
    console.log(r);
}
await main();

Output:

Wait 1000ms.
1000
Wait 2000ms.

I want to stop the remaining code except the code that was executed first through Promise.race.

Is there any other way?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The only way to do something like this would be to put the code that runs conditionally near where you call the Promise.

function delay(time) {
    return new Promise(function (resolve) {
        setTimeout(resolve, time, time);
    })
}

async function main() {
    const firstResult = await Promise.race([
        delay(1000),
        delay(2000),
    ]);
    console.log(`Wait ${firstResult}ms.`);
}
main();

If the code you want to run conditionally is inside a function - like with your original delay function - and the function doesn't explicitly provide a way to change its execution after being called - then no, there's nothing you can do to keep that code from executing.

Most of the time when Promises are involved, no such method exists - though there are exceptions, such as with AbortController.

about 4 years ago · Santiago Trujillo 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!