Home > Software engineering >  How to reject child Promise using AbortController
How to reject child Promise using AbortController

Time:08-28

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:

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>

CodePudding user response:

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>

  • Related