Promise Deferred With Resolve Reject

Create a deferred promise with external resolve and reject for event-driven async coordination.

TypescriptResilience

Code

typescriptsnippet
1 line
export class Deferred<T>{readonly promise:Promise<T>;resolve!:(value:T)=>void;reject!:(reason:Error)=>void;settled=false;constructor(){this.promise=new Promise<T>((resolve,reject)=>{this.resolve=(v)=>{if(!this.settled){this.settled=true;resolve(v);}};this.reject=(e)=>{if(!this.settled){this.settled=true;reject(e);}};});}}export function allDeferred<T>(deferreds:Deferred<T>[]):Promise<T[]>{return Promise.all(deferreds.map(d=>d.promise));}export function raceDeferred<T>(deferreds:Deferred<T>[]):Promise<T>{return Promise.race(deferreds.map(d=>d.promise));}

Inside the snippet

Promise Deferred With Resolve Reject keeps everything in the class Deferred and the functions allDeferred and raceDeferred.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Putting it to use

Treat Deferred as the API: import it, and ignore the supporting code.

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `allDeferred`, `raceDeferred` at load time.