useAbortController – A React Hook to work with the AbortController

Kent C. Dodds recently floated this snippet around, a React Hook to easily work with the the AbortController:

function useAbortController() {
  const abortControllerRef = React.useRef()
  const getAbortController = React.useCallback(() => {
    if (!abortControllerRef.current) {
      abortControllerRef.current = new AbortController()
    return abortControllerRef.current
  }, [])

  React.useEffect(() => {
    return () => getAbortController().abort()
  }, [getAbortController])

  const getSignal = React.useCallback(() => getAbortController().signal, [

  return getSignal;

💁‍♂️ The AbortController is a Web API which allows you to cancel JavaScript promises.

JavaScript asyncawait: Resolving Promises in parallel

Recently I saw a colleague implement some functionality in which he required two results from an API using asyncawait. The piece of code looked something like this:

The code looks fine, is syntactically correct, and works … but there’s one big problem with it: the calls are made sequentially.

To run these calls – which are promises – in parallel, one can reside to using Promise.all.

As per MDN Docs:

The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

Combine that with destructuring and the code becomes this:

async function fetchData() {
    const [result1, result2] = await Promise.all([

    // ...

Easy, right?

💻 The example embedded in this post is part of a talk on ESNext named “What’s next
 for JavaScript?”, which I recently gave at a Fronteers België meetup and Frontend United 2018 (Utrecht). You can check out the slides / a recording of that talk right here. I’m available for bringing this talk at your meetup/conference.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Cancel a JavaScript Promise with AbortController

👋 This post also got published on Medium. If you like it, please give it some love a clap over there.

In How to Cancel Your Promise Seva Zaikov has done a nice writeup exploring several attempts on how to cancel promises. After also touching generators and async/await the conclusion is that you can’t actually cancel a promise with the techniques mentioned (you may introduce some workarounds to track the cancelled state yourself, yet that won’t actually cancel an ongoing promise).

At the end of the article the author mentions abortable fetch, but doesn’t dig deeper into it. A shame though, as the shiny AbortController – the driving force behind the abortable fetch – is something which will allow you to actually cancel any promise (and not just fetch)!

To use the AbortController, create an instance of it, and pass its signal into a promise.

// Creation of an AbortController signal
const controller = new AbortController();
const signal = controller.signal;

// Call a promise, with the signal injected into it
doSomethingAsync({ signal })
	.then(result => {
	.catch(err => {
		if ( === 'AbortError') {
			console.log('Promise Aborted');
		} else {
			console.log('Promise Rejected');

Inside the actual promise you listen for the abort event to be fired on the given signal, upon which the promise will be cancelled.

// Example Promise, which takes signal into account
function doSomethingAsync({signal}) {
	if (signal.aborted) {
		return Promise.reject(new DOMException('Aborted', 'AbortError'));

	return new Promise((resolve, reject) => {
		console.log('Promise Started');

		// Something fake async
		const timeout = window.setTimeout(resolve, 2500, 'Promise Resolved')

		// Listen for abort event on signal
		signal.addEventListener('abort', () => {
			reject(new DOMException('Aborted', 'AbortError'));

With this set up, you can call controller.abort(); from anywhere you like in order to abort/cancel the promise:

document.getElementById('stop').addEventListener('click', (e) => {

Below is a combined example with two buttons. The “start” button starts a promise which resolves after 2.5 seconds. When hitting “stop/abort” during that timeframe however, the promise will be cancelled.

See the Pen AbortController Example by Bramus (@bramus) on CodePen.

My personal nitpick with AbortController is the fact that it’s part of the DOM spec, and not the ECMAScript Spec. This makes it a browser feature, not a language feature. There once was a proposal for cancelable promises, yet it got withdrawn at Stage-1.

AbortController is available in Firefox 57 and Edge 16. Chrome and Safari are still working on it.

MDN: AbortController
WhatWG DOM Spec: Aborting Ongoing Activities →

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.