As Promise can't be canceled we can just unsubscribe from its result when don't need it.
Using yarn
yarn add pietile-promise-observer
or using npm
npm install -S pietile-promise-observer
import { PromiseObserver, PromiseResult } from "pietile-promise-observer";
function asyncAction(): Promise<number> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Math.random());
}, 1000);
});
}
function resultHandler(result: PromiseResult<number>): void {
if (result.error) {
// Smth wrong happened
console.log("Error :(", result.error.message);
return;
}
console.log(result.value + 1);
}
const promiseObserver = new PromiseObserver<number>();
promiseObserver.subscribe(asyncAction(), resultHandler);
// Somehwere later ...
promiseObserver.subscribe(asyncAction(), resultHandler);
// or
promiseObserver.unsubscribe();
Create new PromiseObserver.
subscribe(promise: Promise<T>, callback: Callback<T>, unsubscribedCallback?: Callback<T>): Promise<T>
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 from subscribed Promise
Is observer awaiting for any promise result?
Static property. When true will warn in console on each rejection. Useful for debugging
Pietile Promise Observer is MIT License.