Reliability · Medium · 15 min

Cut slow calls with AbortController

A saturated model server can take minutes. Set a time limit and actually cancel the request.

Write withTimeout(promiseFn, ms). Create an AbortController, call promiseFn(signal) and return its result. If it takes longer than ms, abort the signal and reject with an Error whose name is 'TimeoutError'. Any other error passes through unchanged.

You already have slowFetch(ms, { signal }), a fake request that answers 'done' after ms milliseconds and honours signal: when aborted it cancels and rejects with an AbortError. It counts cancellations in window.__aborted.

Challenges 0/4

  • Returns the result when it arrives in time
  • Rejects with TimeoutError when too slow
  • Cancels the slow request (aborts the signal)
  • Lets other errors through

async function withTimeout(promiseFn, ms) {
  // 1. const controller = new AbortController()
  // 2. abort it after ms with setTimeout
  // 3. turn the abort into an Error named 'TimeoutError'
  return promiseFn();
}

withTimeout((signal) => slowFetch(300, { signal }), 30)
  .then(console.log, (e) => console.log(e.name, e.message));
Console output appears here (console.log).

Go deeper: the MDN reference →

This in production, with your data? Let's talk for 15 minutes →