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

Viewed 26

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?

1 Answers

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.

Related