pax_global_header00006660000000000000000000000064131254713440014516gustar00rootroot0000000000000052 comment=0ea492a3a02e5b8bb984b7a7f1db60a31f66da0b p-cancelable-0.3.0/000077500000000000000000000000001312547134400140245ustar00rootroot00000000000000p-cancelable-0.3.0/.editorconfig000066400000000000000000000002761312547134400165060ustar00rootroot00000000000000root = true [*] indent_style = tab end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [{package.json,*.yml}] indent_style = space indent_size = 2 p-cancelable-0.3.0/.gitattributes000066400000000000000000000000351312547134400167150ustar00rootroot00000000000000* text=auto *.js text eol=lf p-cancelable-0.3.0/.gitignore000066400000000000000000000000151312547134400160100ustar00rootroot00000000000000node_modules p-cancelable-0.3.0/.travis.yml000066400000000000000000000000531312547134400161330ustar00rootroot00000000000000language: node_js node_js: - '6' - '4' p-cancelable-0.3.0/index.js000066400000000000000000000025111312547134400154700ustar00rootroot00000000000000'use strict'; class CancelError extends Error { constructor() { super('Promise was canceled'); this.name = 'CancelError'; } } class PCancelable { static fn(fn) { return function () { const args = [].slice.apply(arguments); return new PCancelable((onCancel, resolve, reject) => { args.unshift(onCancel); fn.apply(null, args).then(resolve, reject); }); }; } constructor(executor) { this._pending = true; this._canceled = false; this._promise = new Promise((resolve, reject) => { this._reject = reject; return executor( fn => { this._cancel = fn; }, val => { this._pending = false; resolve(val); }, err => { this._pending = false; reject(err); } ); }); } then() { return this._promise.then.apply(this._promise, arguments); } catch() { return this._promise.catch.apply(this._promise, arguments); } cancel() { if (!this._pending || this._canceled) { return; } if (typeof this._cancel === 'function') { try { this._cancel(); } catch (err) { this._reject(err); } } this._canceled = true; this._reject(new CancelError()); } get canceled() { return this._canceled; } } Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); module.exports = PCancelable; module.exports.CancelError = CancelError; p-cancelable-0.3.0/license000066400000000000000000000021371312547134400153740ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. p-cancelable-0.3.0/package.json000066400000000000000000000014221312547134400163110ustar00rootroot00000000000000{ "name": "p-cancelable", "version": "0.3.0", "description": "Create a promise that can be canceled", "license": "MIT", "repository": "sindresorhus/p-cancelable", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=4" }, "scripts": { "test": "xo && ava" }, "files": [ "index.js" ], "keywords": [ "promise", "cancelable", "cancel", "canceled", "canceling", "cancellable", "cancellation", "abort", "abortable", "aborting", "cleanup", "task", "token", "async", "function", "await", "promises", "bluebird" ], "devDependencies": { "ava": "*", "delay": "^2.0.0", "xo": "*" } } p-cancelable-0.3.0/readme.md000066400000000000000000000063311312547134400156060ustar00rootroot00000000000000# p-cancelable [![Build Status](https://travis-ci.org/sindresorhus/p-cancelable.svg?branch=master)](https://travis-ci.org/sindresorhus/p-cancelable) > Create a promise that can be canceled Useful for animation, loading resources, long-running async computations, async iteration, etc. ## Install ``` $ npm install --save p-cancelable ``` ## Usage ```js 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); ``` ## API ### new PCancelable(executor) Same as the [`Promise` constructor](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise), but with a prepended `onCancel` parameter in `executor`. `PCancelable` is a subclass of `Promise`. #### onCanceled(fn) Type: `Function` Accepts a function that is called when the promise is canceled. You're not required to call this function. ### PCancelable#cancel() Type: `Function` Cancel the promise. The cancellation is synchronous. Calling it after the promise has settled or multiple times does nothing. ### PCancelable#canceled Type: `boolean` Whether the promise is canceled. ### PCancelable.CancelError Type: `Error` Rejection reason when `.cancel()` is called. ### PCancelable.fn(fn) Convenience method to make your promise-returning or async function cancelable. The function you specify will have `onCancel` prepended to its parameters. ```js const fn = PCancelable.fn((onCancel, input) => { const job = new Job(); onCancel(() => { job.cleanup(); }); return job.start(); //=> Promise }); const promise = fn('input'); //=> PCancelable // … promise.cancel(); ``` ## FAQ ### Cancelable vs. Cancellable [In American English, the verb cancel is usually inflected canceled and canceling—with one l.](http://grammarist.com/spelling/cancel/)
Both a [browser API](https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable) and the [Cancelable Promises proposal](https://github.com/tc39/proposal-cancelable-promises) use this spelling. ### What about the official [Cancelable Promises proposal](https://github.com/tc39/proposal-cancelable-promises)? ~~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. ## Related - [p-lazy](https://github.com/sindresorhus/p-lazy) - Create a lazy promise that defers execution until `.then()` or `.catch()` is called - [More…](https://github.com/sindresorhus/promise-fun) ## License MIT © [Sindre Sorhus](https://sindresorhus.com) p-cancelable-0.3.0/test.js000066400000000000000000000044131312547134400153430ustar00rootroot00000000000000import test from 'ava'; import delay from 'delay'; import PCancelable from '.'; const fixture = Symbol('fixture'); test('new PCancelable()', async t => { t.plan(5); const p = new PCancelable((onCancel, resolve) => { onCancel(() => { t.pass(); }); setTimeout(() => { resolve(fixture); }, 50); }); t.true(p instanceof Promise); t.false(p.canceled); p.cancel(); await t.throws(p, PCancelable.CancelError); t.true(p.canceled); }); test('calling `.cancel()` multiple times', async t => { t.plan(2); const p = new PCancelable((onCancel, resolve) => { onCancel(() => { t.pass(); }); setTimeout(() => { resolve(fixture); }, 50); }); p.cancel(); p.cancel(); try { await p; } catch (err) { p.cancel(); t.true(err instanceof PCancelable.CancelError); } }); test('no `.cancel()` call', async t => { const p = new PCancelable((onCancel, resolve) => { onCancel(() => { t.fail(); }); setTimeout(() => { resolve(fixture); }, 50); }); t.is(await p, fixture); }); test('no `onCancel` handler', async t => { t.plan(1); const p = new PCancelable((onCancel, resolve) => { setTimeout(() => { resolve(fixture); }, 50); }); p.cancel(); await t.throws(p, PCancelable.CancelError); }); test('does not do anything when the promise is already settled', async t => { t.plan(2); const p = new PCancelable((onCancel, resolve) => { onCancel(() => { t.fail(); }); resolve(); }); t.false(p.canceled); await p; p.cancel(); t.false(p.canceled); }); test('PCancelable.fn()', async t => { t.plan(2); const fn = PCancelable.fn(async (onCancel, input) => { onCancel(() => { t.pass(); }); await delay(50); return input; }); const p = fn(fixture); p.cancel(); await t.throws(p, PCancelable.CancelError); }); test('PCancelable.CancelError', t => { t.true(PCancelable.CancelError.prototype instanceof Error); }); test('rejects when canceled', async t => { const p = new PCancelable(onCancel => { onCancel(() => {}); }); p.cancel(); await t.throws(p, PCancelable.CancelError); }); test('rejects when canceled after a delay', async t => { const p = new PCancelable(onCancel => { onCancel(() => {}); }); setTimeout(() => { p.cancel(); }, 100); await t.throws(p, PCancelable.CancelError); });