Categories
JavaScript Answers

How to cancel a promise with JavaScript?

Spread the love

To cancel a promise with JavaScript, we use the AbortController constructor.

For instance, we write

const controller = new AbortController();

const task = new Promise((resolve, reject) => {
  //...
  controller.signal.addEventListener("abort", () => {
    reject();
  });
});

controller.abort();

to create an AbortController object.

Then we create the promise with the Promise constructor called with a callback.

In it, we listen to the abort controller’s abort event by calling controller.signal.addEventListener in the task promise.

We call it with a callback that calls reject to reject the promise, which stops the promise from running.

Then we call controller.abort to cancel the promise, which triggers the abort event on the controller.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *