How to cancel a promise:
We can cancel a promise using AbortController object
You can create a new AbortController
object using the AbortController
constructor. Communicating with a DOM request is done using an AbortSignal object.
Code explanation:
(1) Created two buttons one for fetching data and another for aborting the operation/promise
(2) Set two function fetchAPI() and abortAPI() on button click.
(3) When a user clicks on the download button,fetchAPI called
(1) Controller object created which has a single property signal
that allows to set event listeners on it.
(2) Pass the signal
property of an AbortController
as a fetch
option
(3) fetch method already aware of how to work with AbortController,
that’s why it will listen abort event on the signal
(4) So when the user clicks on the download button, the fetch method starts fetching the data and when the user clicks on the abort button and if a promise is not completed then it gets canceled immediately with AbortError, so make sure you are handling it with try and catch block.
(4) When the abort button is clicked:
controller.abort() and this event is sent to fetch via signal and abort the request.
Note:
(1) AbortController works with any asynchronous task.
(2) Axios also support AbortController.
(3) You can pass an optional reason for aborting to the abort method. If you don’t include a reason for the cancellation, it defaults to the AbortError
(4) You can use AbortSignal to abort cancelable asynchronous processes on timeout.
I hope this article help you understand AbortController better. Feel free to give you valuable feedback.
Thanks and regards
Saurav Kumar Sharma