Cancel a JavaScript Promise with AbortController

In How to Cancel Your Promise Seva Zaikov has done a nice writeup on several techniques on how to cancel promises. After also touching generators and async/await the conclusion is that you can’t (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 => {
		console.log(result);
	})
	.catch(err => {
		if (err.name === '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', () => {
			window.clearTimeout(timeout);
			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) => {
	e.preventDefault();
	controller.abort();
});

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 →

Original Content , ,

Leave a Reply

Your email address will not be published. Required fields are marked *