Skip to content

.tip

· one of the small things

Combine a timeout and a disconnect with AbortSignal.any

A handler has two reasons to stop early: the deadline passed, or the client went away. Watch one and the other leaves an upstream call running that nobody is waiting for. AbortSignal.any folds signals into one that aborts as soon as the first of them does.

const signal = AbortSignal.any([request.signal, AbortSignal.timeout(5000)]);
const res = await fetch(upstreamUrl, { signal });

It is in Node from 20.3 and in every current browser, and the rejection says which reason won, since the timeout aborts with a TimeoutError.

javascriptconcurrency