AbortController API

Abort controller API

One of the most frequent problems when dealing with asynchronous functions is managing the cancellation of HTTP requests. 

When, for instance, the user changes page before the data fetching is complete, it is useful to cancel the request to save resources. This is where the AbortController comes to our aid.


What it is and How to use it

It is an interface that allows you to cancel one or more requests. This controller generates a signal, which is passed to the asynchronous function. This way, we will save bandwidth, reduce the load on the server, and the application will be able to react more quickly to navigation. 

When we want to interrupt an operation, it is sufficient to create an instance of AbortController. This will provide us with an AbortSignal object that we will use to communicate with the asynchronous operation. Then, simply use the abort() method, and the listening operation will stop and throw an exception. 

The fetch function is called, and the signal is passed to it as an option.

By calling controller.abort(), the Promise will be rejected.


Multiple Aborts

The ability to apply the same signal to multiple operations is very useful, allowing you to abort them with a single method.

When the controller.abort() method is called, all operations that share the same signal are terminated.. 


Reason

The abort() method accepts an optional parameter that can be any valid JavaScript value. If not provided, the default value is a DOMException “AbortError”. The reason can then be retrieved from the signal

Whereas, if no parameter is provided, the log will return:

Considerations

In terms of compatibility, AbortController and signal are widely supported by browsers.

The AbortController can be integrated into wrapper functions to make its use more convenient in an application, keeping the code clean.

Although in some cases the improvement in user experience may not benefit from significant enhancements, it is always good practice to limit the execution of unnecessary code. 

In all other cases, however, canceling requests that have become unnecessary will increase performance and improve the user experience.


Doc

Repo and demo 


Main Author: Gianluca La Rosa, Front-end Developer @ Bitrock

Do you want to know more about our services? Fill in the form and schedule a meeting with our team!