Async Timeout Wrapper

Race a promise against a timer so a slow dependency cannot hold a request open indefinitely, aborting the underlying signal when the deadline passes.

JavascriptResilience

Code

javascriptsnippet
16 lines
export async function withTimeout(promiseFactory, timeoutMs, signal) {
  const controller = new AbortController();
  if (signal) signal.addEventListener("abort", () => controller.abort());
  let timer;
  const timerPromise = new Promise((_, reject) => {
    timer = setTimeout(() => {
      controller.abort();
      reject(new Error("operation timed out after " + timeoutMs + "ms"));
    }, timeoutMs);
  });
  try {
    return await Promise.race([promiseFactory(controller.signal), timerPromise]);
  } finally {
    clearTimeout(timer);
  }
}

How it works

Count the function withTimeout as the entire surface area of Async Timeout Wrapper.

Await points sequence the asynchronous work; a rejection lands at the awaiting line.

Using it

The main signature reads export async function withTimeout(promiseFactory, timeoutMs, signal)

The surface worth importing is withTimeout; the helpers around it are private to the snippet.

Key statements

return await Promise.race([promiseFactory(controller.signal), timerPromise]);
if (signal) signal.addEventListener("abort", () => controller.abort());
const timerPromise = new Promise((_, reject) => {
timer = setTimeout(() => {
controller.abort();
reject(new Error("operation timed out after " + timeoutMs + "ms"));
}, timeoutMs);
});

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `withTimeout` at load time.