Tuesday, May 31, 2022

JavaScript Abort Signal & Semaphore

Abort Signal

The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a fetch request) and abort it if required via an AbortController object.


fetch returns a promise. And JavaScript generally has no concept of “aborting” a promise. So how can we cancel an ongoing fetch? E.g. if the user actions on our site indicate that the fetch isn’t needed any more.

There’s a special built-in object for such purposes: AbortController. It can be used to abort not only fetch, but other asynchronous tasks as well.


“abort” enables sending a signal to an awaited function to stop processing, i.e. in case the API response takes a while to finish and connection is closed by client (i.e. UI cancel button or similar).
In such case it is useful to stop sub-processing.Potentially long running processing could benefit from being able to receive such “signal”.

With node.js version 18 the message can also include “reason”, so it has almost perfect symmetry with “throw error”. Throw can send custom error object “up the caller stack”, while “abort” can send message “down the stack”. It could be useful.


an alternative, open source library

Semaphore @GitHub

A promise-based semaphore implementation suitable to be used with async/await.

This package can be used to synchronize functions that span multiple iterations of the event loop and prevent other code from being executed while your function is waiting.



good podcast discussion and links:




Google Analytics alternative that protects your data and your customers' privacy

Take back control with Matomo – a powerful web analytics platform that gives you 100% data ownership.




No comments: