The Promise.race()
method accepts an array (or any other iterable) of promises as a parameter. It returns a Promise
object that is fulfilled or rejected once the first input promise is fulfilled or rejected:
Promise
object is fulfilled with that value.Promise
object is rejected with that reason.Promise.race()
can be used to race multiple promises against each other and find the first promise to settle.
I am curious. Do you know about any actual use cases for Promise.race? I had no need to use that ever.
I am curious. Do you know about any actual use cases for Promise.race? I had no need to use that ever.
A common use case for racing promises is to create a time out on the client. You can send a request and race that request with a timeout of whatever length you give it, passing Promise.reject
to the timeout handler.
@Daniel: I've almost never used Promise.race()
either, but this course wouldn't have been complete without it.
As Ian and I mentioned, racing a promise against a timeout promise is a possible use case. Another scenario might be fetching the same information from two different sources and only waiting for the faster response.
I get an error message: TypeError: Promise.race(...).finally is not a function
function resolveAfter(ms, value) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(value);
}, ms);
});
}
function timeout(ms, measuringPromise) {
let timeoutID;
const timeoutPromise = new Promise((_, reject) => {
timeoutID = setTimeout(() => {
reject(Error(`Timed out after ${ms}ms`));
}, ms);
});
return Promise.race([somePromise, timeoutPromise]).finally(() => {
clearTimeout(timeoutID);
});
}
const somePromise = resolveAfter(1000, 'Some Content');
timeout(2000, somePromise).then(
(value) => console.log(value),
(err) => console.warn(error.message),
);
Node v8.17.0, MacOS Catalina v10.15.6
@Erkan: The Promise.prototype.finally
method is only supported as of Node v10.0.0 (see https://node.green/#ES2018-features-Promise-prototype-finally).
thank you very much, that must have been the scotch at that time, alread got it,..