1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Create A Cancelable Promise With PCancelable as a javascript til

This commit is contained in:
jbranchaud
2018-05-31 09:52:35 -05:00
parent 97760264e9
commit 70050e24a9
2 changed files with 41 additions and 1 deletions

View File

@@ -0,0 +1,39 @@
# Create A Cancelable Promise With PCancelable
If an async task takes a really long time and we find out in the middle of
its execution that we no longer want the results of that activity, it would
be nice to be able to cancel that promise. There was a [proposal for
cancelable promises](https://github.com/tc39/proposal-cancelable-promises),
but it has since been withdrawn. There is an alternative though.
The [`p-cancelable`](https://github.com/sindresorhus/p-cancelable) package
provides a promise wrapper that acts as a cancelable promise.
```javascript
import PCancelable from 'p-cancelable';
const fetchPromise = new PCancelable((resolve, reject, onCancel) => {
setTimeout(() => {
resolve({ ok: true, data: [1, 2, 3] });
}, 10000);
onCancel(() => {
console.log('This promise is being canceled');
});
});
fetchPromise.then(response => {
console.log('Promises Resolved: ', response.data);
}).catch(err => {
console.log('Promises Rejected: ', err);
});
fetchPromise.cancel();
```
We can create a promise in a familiar manner. We get an additional argument
-- the `onCancel` function. This is a function that will be executed if
`cancel` is called before the promises has resolved or rejected. In the
above example, the `fetchPromise.cancel()` line will be invoked before the
`setTimeout` resolves. The promise will be canceled, causing a rejection
which will push us into the `catch` handler.