type ResolveFn = (data: T) => void; type RejectFn = (err: unknown) => void; interface PromiseResolveReject { readonly resolve: (value: T) => void, readonly reject: (err: unknown) => void, }; const createPromiseValue = (): [PromiseResolveReject, Promise] => { let resolve: ResolveFn | null = null; let reject: RejectFn | null = null; const promise: Promise = new Promise((localResolve: ResolveFn, localReject: RejectFn) => { resolve = localResolve; reject = localReject; }); if (resolve === null) { throw Error('createPromiseValue - resolve is null'); } if (reject === null) { throw Error('createPromiseValue - reject is null'); } const promiseValue = { resolve, reject, }; return [promiseValue, promise]; }; export class PromiseBoxRace { private promiseResolveReject: PromiseResolveReject | null = null; readonly promise: Promise; constructor() { const [promiseResolveReject, promise] = createPromiseValue(); this.promiseResolveReject = promiseResolveReject; this.promise = promise; } resolve = (value: T) => { const promiseResolveReject = this.promiseResolveReject; this.promiseResolveReject = null; if (promiseResolveReject === null) { return; } promiseResolveReject.resolve(value); } reject = (err?: unknown) => { const promiseResolveReject = this.promiseResolveReject; this.promiseResolveReject = null; if (promiseResolveReject === null) { return; } promiseResolveReject.reject(err); } isFulfilled = (): boolean => { return this.promiseResolveReject === null; } }