I have read many different ways of adding timeouts within a promise, but most, if not all, seem to utilise the setTimeout()
method. By definition:
The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
What I am looking for is a way to say:
"If the function executed inside the promise (that will either resolve or
reject the promise), does not complete within a specified x number of
milliseconds, automatically reject or raise an exception."
If this is the same as the defined above (using the setTimeout()
method), an explanation would be highly appreciated!
You can wrap setTimeout
in a Promise and create a little "wait"-function which you can then use with Promise.race
:
function wait(ms) {
return new Promise((_, reject) => {
setTimeout(() => reject(new Error('timeout succeeded')), ms);
});
}
try {
const result = await Promise.race([wait(1000), yourAsyncFunction()]);
} catch(err) {
console.log(err);
}
With this code Promise.race
will reject if yourAsyncFunction
takes longer than 1000 ms
to resolve/reject, otherwise result
will yield the resolved value from yourAsyncFunction
.