DEV Community

Fernando Souza
Fernando Souza

Posted on

AbortController (Cancelable Async Code)

  • Why do we need a way to cancel async code?
  • Real life examples;
  • Are there other libs that support canceling signal?
  • Are there other libs that implement a different way of cancelation?

The fetch api has already implemented an option to pass down the signal object but you can explicitly implement to your own Promise code.

Example 1: Manually aborting an async request.

// 1. We instantiate the abort controller
const abortController = new AbortController();

// 2. We pass down the signal object to the async code we need to control.
function asyncCode(abortSignal) {
  return new Promise((resolve, reject) => {
    const timeOut = setTimeout(() => {
      resolve("done");
    }, 5000);

    // 3. We listen to the signal abort event and do what is needed.
    abortSignal.addEventListener("abort", () => {
      clearTimeout(timeOut);
      reject("Fetch was aborted");
    });
  });
}

asyncCode(abortController.signal)
    .then(console.log)
    .catch(console.log);

setTimeout(() => {
  // 4. We can call the abort method anywhere outside of the async code.
  abortController.abort();
}, 2000);

Enter fullscreen mode Exit fullscreen mode

Canceling a fetch request

The fetch() function can receive an signal and trows an "TimeoutError" when it aborts.

try {
    await fetch('url...', { signal: AbortSignal.timeout(3000) });
} catch(e) {
    if (e.name === 'TimeoutError') {
        console.log('The request took more than 3 seconds to complete');
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)