Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/wojtekmaj/make-cancellable-promise
Make any Promise cancellable.
https://github.com/wojtekmaj/make-cancellable-promise
promise promise-cancelling
Last synced: 3 months ago
JSON representation
Make any Promise cancellable.
- Host: GitHub
- URL: https://github.com/wojtekmaj/make-cancellable-promise
- Owner: wojtekmaj
- License: mit
- Created: 2019-07-17T10:46:40.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2024-04-15T15:41:33.000Z (9 months ago)
- Last Synced: 2024-05-02T05:33:24.206Z (9 months ago)
- Topics: promise, promise-cancelling
- Language: TypeScript
- Homepage:
- Size: 3.43 MB
- Stars: 26
- Watchers: 3
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
[![npm](https://img.shields.io/npm/v/make-cancellable-promise.svg)](https://www.npmjs.com/package/make-cancellable-promise) ![downloads](https://img.shields.io/npm/dt/make-cancellable-promise.svg) [![CI](https://github.com/wojtekmaj/make-cancellable-promise/actions/workflows/ci.yml/badge.svg)](https://github.com/wojtekmaj/make-cancellable-promise/actions)
# Make-Cancellable-Promise
Make any Promise cancellable.
## tl;dr
- Install by executing `npm install make-cancellable-promise` or `yarn add make-cancellable-promise`.
- Import by adding `import makeCancellablePromise from 'make-cancellable-promise`.
- Do stuff with it!
```ts
const { promise, cancel } = makeCancellablePromise(myPromise);
```## User guide
### makeCancellablePromise(myPromise)
A function that returns an object with two properties:
`promise` and `cancel`. `promise` is a wrapped around your promise. `cancel` is a function which stops `.then()` and `.catch()` from working on `promise`, even if promise passed to `makeCancellablePromise` resolves or rejects.
#### Usage
```ts
const { promise, cancel } = makeCancellablePromise(myPromise);
```Typically, you'd want to use `makeCancellablePromise` in React components. If you call `setState` on an unmounted component, React will throw an error.
Here's how you can use `makeCancellablePromise` with React:
```tsx
function MyComponent() {
const [status, setStatus] = useState('initial');useEffect(() => {
const { promise, cancel } = makeCancellable(fetchData());promise.then(() => setStatus('success')).catch(() => setStatus('error'));
return () => {
cancel();
};
}, []);const text = (() => {
switch (status) {
case 'pending':
return 'Fetching…';
case 'success':
return 'Success';
case 'error':
return 'Error!';
default:
return 'Click to fetch';
}
})();return
{text}
;
}
```## License
The MIT License.
## Author