Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/preco21/pcancel
Wrap promise function into cancelable promise function
https://github.com/preco21/pcancel
cancel cancelable cancellation p promise
Last synced: 6 days ago
JSON representation
Wrap promise function into cancelable promise function
- Host: GitHub
- URL: https://github.com/preco21/pcancel
- Owner: preco21
- License: mit
- Created: 2017-05-24T02:20:12.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2018-01-11T05:33:44.000Z (almost 7 years ago)
- Last Synced: 2024-10-30T16:11:57.943Z (16 days ago)
- Topics: cancel, cancelable, cancellation, p, promise
- Language: JavaScript
- Size: 40 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# pcancel
[![Code Style Prev](https://img.shields.io/badge/code%20style-prev-32c8fc.svg)](https://github.com/preco21/eslint-config-prev)
[![NPM Version](https://img.shields.io/npm/v/pcancel.svg)](https://www.npmjs.com/package/pcancel)
[![Build Status](https://travis-ci.org/preco21/pcancel.svg?branch=master)](https://travis-ci.org/preco21/pcancel)
[![Dependency Status](https://dependencyci.com/github/preco21/pcancel/badge)](https://dependencyci.com/github/preco21/pcancel)> Wrap promise function into cancelable promise function
Sometimes you may need to create cancelable promise for situation like to avoid [isMounted antipattern in React](https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html). `pcancel` provides simple utility for creating cancelable promises. Highly inspired from [this comment](https://github.com/facebook/react/issues/5465#issuecomment-157888325).
## Install
```bash
$ npm install pcancel
```## Usage
```javascript
import pcancel from 'pcancel';const delayC = pcancel(delay);
const p = delayC(4000)
.promise
.then(() => console.log('Yey!'))
.catch((err) => console.error(err));p.cancel(); // Error: Promise has canceled
function delay(time) {
return new Promise((resolve) => setTimeout(() => resolve(), time));
}
```## API
### pcancel(fn[, options])
* `fn` Function - Promise-returning function that will be cancelable.
* `options` Object (optional)
* `noReject` Boolean - Whether to reject when canceling. If this option is `true`, the promise will be resolved with the value passed through to `cancel()` method on the promise.Returns a wrapped function that returns object includes `Promise` instance and `cancel()` function.
You can also specify error or value through `cancel()` method, the specified value will be returned instead of value of the promise:
```javascript
p.cancel(new Error('Foo')); // Error: Foo
```**Note:** `cancel()` rejects the promise immediately when it called.
## License
[MIT](https://preco.mit-license.org/)