A Simple Implementation of Abortable Promise
npm install simple-abortable-promiseA 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.
``bash`
npm install simple-abortable-promise
There are 2 ways to create an AbortablePromise:
#### Constructor
`typescript`
const abortablePromise = new AbortablePromise
// ...
});
#### Create from an existing Promise
`typescript`
const abortablePromise = AbortablePromise.from(promise);
`typescript
// Abort with default reason - Aborted
abortablePromise.abort();
// Abort with custom reason
abortablePromise.abort('I abort it');
`
`typescript
const loadData = (id: number) => {
retrun new AbortablePromise((resolve, reject, abortSignal) => {
fetch(url, { signal: abortSignal })
.then(response => response.json())
.then(parseJsonToData)
.then(resolve)
.catch(reject);
});
}
const abortablePromise = loadData(id);
abortablePromise.abort();
`
`typescript``
const abortablePromise = new AbortablePromise((resolve, reject, abortSignal) => {
abortSignal.addEventListener('abort', () => {
// Do something
});
// ...
});
More background explain is available on my blog.