Skip to content

How to cancel a Promise in JavaScript

Last updated on February 28, 2020

Guys, I would like to share this idea of canceling a promise in JavaScript. Since I know most of the times we might have encountered this situation but finally we ended up saying Promise is not a cancellable one.

Yes. Of course. Promise is not a cancellable one but recent version of JavaScript helps to overcome this with the experimental operator, calledAbortController.

Why Promise?

As we all know, Promise is for executing asynchronous action mainly for calling APIs (dealing with data from different server).

Why to Cancel a Promise?

In some time, we would need to wait for a long time to get data back from an API whereas the end-user might not want it that fashion. Here canceling comes as a rescue for this use-case.

Code

Let’s take a took at the main aspect of this post for knowing how to cancel a promise. You might have seen a blank screen where our target is not UI only JavaScript code, so open up the browser console window and see the results.

In this code, I have tried to showcase the scenario of canceling after particular seconds elapsed. In every 1sec interval, we call an API which we are canceling after 3sec complete. This results in only 3 API result data we got back.

You can try it out with the attached link. If we’re using React.js front-end library therefore this solution will fit into directly without altering anything. If any queries, please post it in the comments section.

References

Published inAngularFrameworksJavaScriptReact