Categories
JavaScript Answers

How to force cancel a promise with JavaScript?

Spread the love

Sometimes, we want to force cancel a promise with JavaScript.

In this article, we’ll look at how to force cancel a promise with JavaScript.

How to force cancel a promise with JavaScript?

To force 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.

Conclusion

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

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 *