Posted 6 months ago. Visible to the public. Repeats. Linked content.

Canceling promises

The cancelable promises proposal was withdrawn some time ago.

The new standard way is that your long-running function take a AbortSignal { signal } property. The caller can use this signal to send an abort request to your function. Upon receiving the request, your function should reject its promise with an error.

Async browser functions like fetch() reject their promises with a new DOMException('Message here', 'AbortError') when canceled.

This already has good browser support and can be polyfilled on older browsers.

Example

Here is an async function countDown(). It returns a promise that will be fulfilled after the given number of seconds:

Copy
function countDown(seconds) { return new Promise((resolve, reject) => { setTimeout(resolve, seconds * 1000) }) }

Here is how you would use it:

Copy
countDown(10).then(() => console.log("10 seconds have past")) // prints "10 seconds have past" after 10 seconds

Making countDown() abortable

Here is a variant of countDown() that may be canceled by the caller before the time has elapsed:

Copy
function countDown(seconds, options = {}) { return new Promise((resolve, reject) => { if (options.signal) { options.signal.addEventListener('abort', (event) => { reject(new DOMException('User aborted countdown', 'AbortError')) }) } setTimeout(resolve, seconds * 1000) }) }

You use it by passing an AbortSignal as a { signal } option:

Copy
let controller = new AbortController() countDown(10, { signal: controller.signal }).then( () => console.log("10 seconds have past"), (reason) => console.log("Countdown failed:", reason) ) controller.abort() // prints "Coundown failed: User aborted countdown" in the next microtask

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Henning Koch
Last edit:
5 months ago
by Jakob Scholz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more