How to time out a promise if failed to complete in time with Node.js?

Sometimes, we want to time out a promise if failed to complete in time with Node.js.

In this article, we’ll look at how to time out a promise if failed to complete in time with Node.js.

How to time out a promise if failed to complete in time with Node.js?

To time out a promise if failed to complete in time with Node.js, we can use the Promise.race method.

For instance, we write

const withTimeout = (millis, promise) => {
  const timeout = new Promise((resolve, reject) =>
    setTimeout(
      () => reject(`Timed out after ${millis} ms.`),
      millis));
  return Promise.race([
    promise,
    timeout
  ]);
}

to define the withTimeout function that calls Promise.race with the promise and the timeout promise.

Promise.race returns the promise that’s settled the earliest so if timeout is settled before promise, it’ll be returned.

Then we can use withTimeout in an async function by writing

await withTimeout(5000, doSomethingAsync());

where doSomethingAsync is an async function.

Conclusion

To time out a promise if failed to complete in time with Node.js, we can use the Promise.race method.