Using AbortSignal in Node.js
July 22, 2021
We recently added the the Web platform AbortController
and AbortSignal
APIs into Node.js and have been busy making
them the idiomatic way of canceling asynchronous operations throughout the Node.js core API. In this post, I introduce
the APIs and illustrate how they can be used. Read More: https://www.nearform.com/blog/using-abortsignal-in-node-js/
example.js
async function someLongRunningTask(options = {}) {
const { signal } = { ...options };
if (signal.aborted === true)
throw new Error('Operation canceled');
const taskDone = new AbortController();
signal.addEventListener('abort', () => {
// logic necessary to cancel the async task
}, {
once: true,
signal: taskDone.signal
});
try {
// ... do the async work
if (signal.aborted)
throw new Error('Operation canceled');
// ... do more async work
} finally {
// Remove the abort event listener to avoid
// leaking memory.
taskDone.abort();
}
}