Sometimes, we want to use Promise.race()
with JavaScript.
In this article, we’ll look at how to use Promise.race()
with JavaScript.
How to use Promise.race() with JavaScript?
To use Promise.race()
with JavaScript, we can call it with an array of promises.
For instance, we write:
const p1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'one');
});
const p2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'two');
});
(async () => {
const value = await Promise.race([p1, p2])
console.log(value);
})()
We call Promise.race
with [p1, p2]
which will return the promise that is settled first.
Therefore, value
should be 'two'
since the setTimeout
callback is run in 100 seconds after the callback is queued for running.
Conclusion
To use Promise.race()
with JavaScript, we can call it with an array of promises.