Kevin 29b9a0c50c clean && clean html base | 4 years ago | |
---|---|---|
.. | ||
index.js | 4 years ago | |
license | 4 years ago | |
package.json | 4 years ago | |
readme.md | 4 years ago |
Create a promise that can be canceled
Useful for animation, loading resources, long-running async computations, async iteration, etc.
$ npm install --save p-cancelable
const PCancelable = require('p-cancelable');
const cancelablePromise = new PCancelable((onCancel, resolve, reject) => {
const worker = new SomeLongRunningOperation();
onCancel(() => {
worker.close();
});
worker.on('finish', resolve);
worker.on('error', reject);
});
cancelablePromise
.then(value => {
console.log('Operation finished successfully:', value);
})
.catch(reason => {
if (cancelablePromise.canceled) {
// Handle the cancelation here
console.log('Operation was canceled');
return;
}
throw reason;
});
// Cancel the operation after 10 seconds
setTimeout(() => {
cancelablePromise.cancel();
}, 10000);
Same as the Promise
constructor, but with a prepended onCancel
parameter in executor
.
PCancelable
is a subclass of Promise
.
Type: Function
Accepts a function that is called when the promise is canceled.
You're not required to call this function.
Type: Function
Cancel the promise. The cancellation is synchronous.
Calling it after the promise has settled or multiple times does nothing.
Type: boolean
Whether the promise is canceled.
Type: Error
Rejection reason when .cancel()
is called.
Convenience method to make your promise-returning or async function cancelable.
The function you specify will have onCancel
prepended to its parameters.
const fn = PCancelable.fn((onCancel, input) => {
const job = new Job();
onCancel(() => {
job.cleanup();
});
return job.start(); //=> Promise
});
const promise = fn('input'); //=> PCancelable
// …
promise.cancel();
In American English, the verb cancel is usually inflected canceled and canceling—with one l.
Both a browser API and the Cancelable Promises proposal use this spelling.
It's still an early draft and I don't really like its current direction. It complicates everything and will require deep changes in the ecosystem to adapt to it. And the way you have to use cancel tokens is verbose and convoluted. I much prefer the more pragmatic and less invasive approach in this module. The proposal was withdrawn.
MIT © Sindre Sorhus