A Simple Implementation of Abortable Promise
This library provides a deadly simple implementation of making Promise
abortable.
That is, an AbortablePromise
is a Promise
with the abitlity to be aborted.
When an AbortablePromise
is aborted, it will reject with an AbortError
.
npm install simple-abortable-promise
There are 2 ways to create an AbortablePromise
:
const abortablePromise = new AbortablePromise<T>((resolve, reject, abortSignal) => {
// ...
});
const abortablePromise = AbortablePromise.from(promise);
// Abort with default reason - Aborted
abortablePromise.abort();
// Abort with custom reason
abortablePromise.abort('I abort it');
const loadData = (id: number) => {
retrun new AbortablePromise<Data>((resolve, reject, abortSignal) => {
fetch(url, { signal: abortSignal })
.then(response => response.json())
.then(parseJsonToData)
.then(resolve)
.catch(reject);
});
}
const abortablePromise = loadData(id);
abortablePromise.abort();
const abortablePromise = new AbortablePromise<Data>((resolve, reject, abortSignal) => {
abortSignal.addEventListener('abort', () => {
// Do something
});
// ...
});
More background explain is available on my blog.