How can I give an asynchronous operation a time limit?
Quick answer
Race the operation against a timer and return a distinct timeout result. If the operation accepts an AbortSignal, abort its controller when the timer expires; otherwise, the timeout may only stop your code from waiting. JavaScript Promises have no built-in cancellation protocol, so check the specific API’s cancellation support. Handle operation errors and clear your timer in a finally block. [S1] [S2]
The question, the details, the next step.
A practical checklist
Choose a timeout duration appropriate for the operation.
Check whether the underlying API accepts and honors an
AbortSignal.Return distinct outcomes for success, operation error, and timeout.
Clear the timer in
finally, and handle errors at the call site.Put resource cleanup in the operation’s own
finallypath.Assume work may continue after timeout unless cancellation is supported.
A few more useful answers
Does `Promise.race()` cancel the operation that loses?
No. It determines which result settles the race first; it does not itself cancel the other Promise. Use the underlying operation’s supported cancellation mechanism if available. [S2]
Can every Promise be stopped with `AbortController`?
What should the timeout result mean to the caller?
It should mean the wrapper’s time limit expired. Unless the underlying operation supports and honors cancellation, it does not prove that the work stopped.
Sources
References used for this guide.
- [S1] Azure Abort Controller client library for JavaScript: cancellation and timeout signals learn.microsoft.com · Checked
- [S2] JavaScript Promise reference: cancellation limitation learn.microsoft.com · Checked
