Contents
AbortController is the standard way to abort any ongoing operations. AbortController and AbortSignal are now part of Nodejs LTS (originally introduced in v15.0.0).
Modern apps usually don’t work in isolation. They interact with entities like other APIs, file system, network, databases, etc. Each of these interactions adds an unknown delay to the handling of the incoming request. Sometimes, these interactions can take long time than expected resulting in overall delay in response. In such cases, the apps need a way to abort any operations that have taken longer than expected.
Cancel Async Operations
Let us take a use case where we want to abort an operation if it takes more than say 10 sec.
|
|
In the above scenario; if fooTask() operation takes longer time than expected say 10 sec, trigger a timeout. There are however two problems with the above code:
- Even though timeout is triggered; the fooTask() operation is not stopped
- Even if fooTask() operation completes within expected time,
setTimeouttimer will still be running and will eventually reject the promise withunhandled promise rejectionerror. This can cause performance/memory issues.
A more graceful way of handling above scenario is
- when timeout is triggered, it sends a signal to abort fooTask() operation
- when fooTask() operation is complete, it sends a signal to clear
setTimeouttimer
This is where AbortController and AbortSignal, now part of Nodejs core API comes into picture.
AbortController & AbortSignal
AbortController is a utility class used to signal cancelation in selected Promise-based APIs. The API is based on the Web API AbortController.
abortController.abort(): Triggers the abort signal, causing the abortController.signal to emit the ‘abort’ event.
abortController.signal: Type: AbortSignal
AbortSignal extends EventTarget with a single type of event that it emits — the abort event. It also has an additional boolean property, aborted which is true if the AbortSignal has already been triggered.
Let us modify our code:
|
|
I have used setTimeout to simulate the operations.
Output with:
- timeout value of
10fortimeoutoperation and100forfooTaskoperation
|
|
- timeout value of
100fortimeoutoperation and10forfooTaskoperation
|
|
Use Cases
Let’s explore some of the practical applications of AbortController:
-
Terminating requests when a user navigates away from the page
-
Canceling requests that exhibit prolonged response times
-
Regulating or delaying fetch requests using throttling or debouncing techniques
-
Effectively managing errors that may arise during request handling
-
Aborting requests during the upload of larger files
Conclusion
AbortController and AbortSignal are now part of Nodejs core APIs. They provide a more graceful way of cancelling async operations.
✨ Thank you for reading and I hope you find it helpful. I sincerely request for your feedback in the comment’s section. You can follow me on twitter @lifeClicks25.
