Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reject child Promise using AbortController

I just learned about how to reject a Promise by using the AbortController API. It’s working fine but when the promise to reject as a "child Promise", this one will still continue running even if the parent Promise is rejected.

Is there a way, when the parent is rejected, to stop the children too?

In this example, this means that there is no more running log after the rejected log when you click on the cancel button:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let controller = new AbortController();

new Promise((resolve, reject) => {
  setInterval(() => console.log("running"), 500)

  controller.signal.addEventListener('abort', () => {
    console.log("rejected")
    reject();
  });

});

function cancel() {
  controller.abort();
}
<button onclick="cancel()">Cancel async loop</button>

>Solution :

Promise and abort controller are fine it’s your timer function that needs to be cleared.

When you declare setInterval it returns an id that can be referenced later to clear the timer.

So, when you reject the promise you need to clear it.

let controller = new AbortController();

new Promise((resolve, reject) => {
  const id = setInterval(() => console.log("running"), 500)

  controller.signal.addEventListener('abort', () => {
    console.log("rejected");
    clearInterval(id);
    reject();
  });

});

function cancel() {
  controller.abort();
}
<button onclick="cancel()">Cancel async loop</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading