p-cancelable
Advanced tools
Comparing version 0.4.1 to 0.5.0
17
index.js
'use strict'; | ||
class CancelError extends Error { | ||
constructor() { | ||
super('Promise was canceled'); | ||
constructor(reason) { | ||
super(reason || 'Promise was canceled'); | ||
this.name = 'CancelError'; | ||
@@ -16,7 +16,6 @@ } | ||
static fn(userFn) { | ||
return function () { | ||
const args = [].slice.apply(arguments); | ||
return (...args) => { | ||
return new PCancelable((resolve, reject, onCancel) => { | ||
args.push(onCancel); | ||
userFn.apply(null, args).then(resolve, reject); | ||
userFn(...args).then(resolve, reject); | ||
}); | ||
@@ -62,3 +61,3 @@ }; | ||
cancel() { | ||
cancel(reason) { | ||
if (!this._isPending || this._isCanceled) { | ||
@@ -73,4 +72,4 @@ return; | ||
} | ||
} catch (err) { | ||
this._reject(err); | ||
} catch (error) { | ||
this._reject(error); | ||
} | ||
@@ -80,3 +79,3 @@ } | ||
this._isCanceled = true; | ||
this._reject(new CancelError()); | ||
this._reject(new CancelError(reason)); | ||
} | ||
@@ -83,0 +82,0 @@ |
{ | ||
"name": "p-cancelable", | ||
"version": "0.4.1", | ||
"version": "0.5.0", | ||
"description": "Create a promise that can be canceled", | ||
@@ -13,3 +13,3 @@ "license": "MIT", | ||
"engines": { | ||
"node": ">=4" | ||
"node": ">=6" | ||
}, | ||
@@ -44,3 +44,3 @@ "scripts": { | ||
"ava": "*", | ||
"delay": "^2.0.0", | ||
"delay": "^3.0.0", | ||
"promise.prototype.finally": "^3.1.0", | ||
@@ -47,0 +47,0 @@ "xo": "*" |
@@ -31,7 +31,6 @@ # p-cancelable [![Build Status](https://travis-ci.org/sindresorhus/p-cancelable.svg?branch=master)](https://travis-ci.org/sindresorhus/p-cancelable) | ||
cancelablePromise | ||
.then(value => { | ||
console.log('Operation finished successfully:', value); | ||
}) | ||
.catch(error => { | ||
(async () => { | ||
try { | ||
console.log('Operation finished successfully:', await cancelablePromise); | ||
} catch (error) { | ||
if (cancelablePromise.isCanceled) { | ||
@@ -44,7 +43,8 @@ // Handle the cancelation here | ||
throw error; | ||
}); | ||
} | ||
})(); | ||
// Cancel the operation after 10 seconds | ||
setTimeout(() => { | ||
cancelablePromise.cancel(); | ||
cancelablePromise.cancel('Unicorn has changed its color'); | ||
}, 10000); | ||
@@ -70,7 +70,7 @@ ``` | ||
### PCancelable#cancel() | ||
### PCancelable#cancel([reason]) | ||
Type: `Function` | ||
Cancel the promise. | ||
Cancel the promise and optionally provide a reason. | ||
@@ -77,0 +77,0 @@ The cancellation is synchronous. Calling it after the promise has settled or multiple times does nothing. |
7032
72