Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/pietile/pietile-promise-observer
Simple Promise observer
https://github.com/pietile/pietile-promise-observer
observer promise
Last synced: about 20 hours ago
JSON representation
Simple Promise observer
- Host: GitHub
- URL: https://github.com/pietile/pietile-promise-observer
- Owner: pietile
- Created: 2019-02-03T17:10:08.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2021-02-15T10:37:11.000Z (almost 4 years ago)
- Last Synced: 2024-04-23T10:45:24.703Z (9 months ago)
- Topics: observer, promise
- Language: TypeScript
- Size: 16.6 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Pietile Promise Observer
[![npm version](https://badgen.net/npm/v/pietile-promise-observer?color=56C838)](https://www.npmjs.com/package/pietile-promise-observer)
[![install size](https://badgen.net/packagephobia/install/pietile-promise-observer)](https://packagephobia.now.sh/result?p=pietile-promise-observer)As Promise can't be canceled we can just unsubscribe from its result when don't need it.
## Installation
Using yarn
```sh
yarn add pietile-promise-observer
```or using npm
```sh
npm install -S pietile-promise-observer
```## Usage example
```tsx
import { PromiseObserver, PromiseResult } from "pietile-promise-observer";function asyncAction(): Promise {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Math.random());
}, 1000);
});
}function resultHandler(result: PromiseResult): void {
if (result.error) {
// Smth wrong happened
console.log("Error :(", result.error.message);
return;
}console.log(result.value + 1);
}const promiseObserver = new PromiseObserver();
promiseObserver.subscribe(asyncAction(), resultHandler);
// Somehwere later ...
promiseObserver.subscribe(asyncAction(), resultHandler);
// or
promiseObserver.unsubscribe();
```## API
### `new PromiseObserver()`
Create new PromiseObserver.
### `subscribe(promise: Promise, callback: Callback, unsubscribedCallback?: Callback): Promise`
Subscribe to `promise`. After the `promise` is resolved the `callback` will be called with either
`{ value: null; error: Error; }` or `{ value: T; error: null; }` argument. Optional `unsubscribedCallback` will be called for unsubscribed promises. Return the same promise.### `unsubscribe(): void`
Unsubscribe from subscribed Promise
### `isSubscribed(): boolean`
Is observer awaiting for any promise result?
### `PromiseObserver.WARN_ON_ERROR`
Static property. When true will warn in console on each rejection. Useful for debugging
## License
Pietile Promise Observer is MIT License.