Deferred - API
A deferred promise that can be manually resolved or rejected.
Installation
- npm
- yarn
- pnpm
npm is the default package manager for Node.js, and to where tscommon is published.
Your project is using npm if it has a
Run the following command in your terminal:
Your project is using npm if it has a
package-lock.json
file in its root folder.Run the following command in your terminal:
terminal
npm install @tscommon/deferred
Usage
- Resolve
- Reject
main.ts
import { Deferred, DeferredState } from '@tscommon/deferred';
async function main(): Promise<void> {
const deferred = new Deferred<number>();
process.nextTick(() => {
deferred.resolve(42);
console.log(deferred.state === DeferredState.Fulfilled); // true
});
const value = await deferred;
console.log(value); // 42
}
main();
main.ts
import { Deferred, DeferredState } from '@tscommon/deferred';
async function main(): Promise<void> {
const deferred = new Deferred<number>();
process.nextTick(() => {
deferred.reject(new Error('Oops!'));
console.log(deferred.state === DeferredState.Rejected); // true
});
await deferred; // Error: Oops!
}
main();