Timeout Race With Abort Signal
Race a promise against a timeout using AbortSignal for cancellable async operations.
Code
export async function timeoutRace<T>(promise:Promise<T>,ms:number,signal?:AbortSignal):Promise<T>{const controller=new AbortController();const onAbort=()=>controller.abort();signal?.addEventListener('abort',onAbort);const timer=setTimeout(()=>controller.abort(),ms);try{return await Promise.race([promise,new Promise<T>((_,reject)=>{controller.signal.addEventListener('abort',()=>reject(new Error('aborted')));})]);}finally{clearTimeout(timer);signal?.removeEventListener('abort',onAbort);}}What the code does
Timeout Race With Abort Signal is built around the functions onAbort and timeoutRace.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Usage notes
timeoutRace is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `onAbort`, `timeoutRace` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.