An extension of native Promises with true abort capabilities via AbortSignal.
npm install @as-any/abortable-promiseThe AbortablePromise class is an extension of the native JavaScript Promise, designed to make it easier to abort promises. It adds an abort signal to the promise, which can trigger rejection of the promise when it's aborted.
Create AbortController and pass its signal as a second argument of AbortablePromise constructor:
``typescript
const controller = new AbortController();
const signal = controller.signal;
const myPromise = new AbortablePromise((resolve, reject) => {
// Do something
}, signal);
`
Or make your existing promise abortable:
`typescript`
const originalPromise = new Promise((resolve, reject) => {
// Do something
});
const myAbortablePromise = makeAbortable(originalPromise, signal);
Then call the abort() method
`typescript`
controller.abort();
Error handling can be done using the catch method just like with regular promises:
`typescript`
myAbortablePromise.catch(reason => {
console.error('Promise was aborted:', reason);
});
By default, AbortablePromise rejects with an "AbortError" DOMException if it is aborted:
`typescript
setTimeout(() => controller.abort(), 1000);
try {
await myAbortablePromise;
} catch (err) {
if (err.name === 'AbortError') {
console.log("Operation aborted: ", err.message);
}
console.log("Error occurred: ", err);
}
`
Pass any custom object you want the promise to be rejected with to controller.abort():
`typescript
myAbortablePromise.catch(reason => {
console.log(reason) // { myReason: 42 }
})
controller.abort({ myReason: 42 });
``