JavaScript is amazing with Promises and async support. However, it comes without native support of timeouts for Promises.
Here is how it can be implemented with Promise.race:
const awaitWithTimeout = (p, timeout) =>
Promise.race([
p,
new Promise((_, err) =>
setTimeout(() => err(
new Error(`Execution timeout ${timeout} reached`)
), timeout)
)
]);
// some long operation that can raise a timeout
const operation = new Promise(() => {});
const timeout = 1000;
await awaitWithTimeout(operation, timeout);
In the code above a first promise to resolve or reject will be returned from the function awaitWithTimeout
. Therefore, if the operation can finish within the defined deadline it will return value from the promise, otherwise, it will raise a timeout error.
Find out more useful content at:
Any feedback, contribution, or help is highly appreciated.
Thanks for your time and happy coding! 👋