Member-only story
This JavaScript API is more powerful than you imagine!
Today, let’s talk about a powerful standard JavaScript API that may have been overlooked by you-AbortController
。
In the past, people mentionedAbortController
When it comes to interrupt requests, examples are usually given, and even the description given by MDN is like this:
howeverAbortController
The ability is not limited to this,AbortController
It is a global class in JavaScript that can be used to terminate any asynchronous operation. The usage method is as follows:
const controller = new AbortController();controller.signal;
controller.abort();
We create aAbortController
After the instance, two things will be obtained:
signal
Attribute, this is aAbortSignal
For instance, we can pass it to the API that needs to be interrupted to respond to the interrupt event and handle it accordingly, for example, by passing it tofetch()
The method can terminate this request;.abort()
Method, calling this method will triggersignal
Suspend the event and mark the signal as aborted.
We can monitor through surveillanceabort
Event, then implement termination based on specific logic:
controller.signal.addEventListener('abort', () => {
//Implement termination logic
});