前言
当有多个共享资源、协同操作的时候,往往需要根据动态亦或是复杂的条件以控制和调用程序逻辑。
设计
- PendingPromise<T>: type Promise<T> & { resolve:(res?:T)=>void, reject:(e: Error):void }
- pendingResolve<T>: ()=>PendingPromise<T>
实现
export type PendingPromise<T> = Promise<T> & { resolve: (T?: any) => void; reject: (e: Error) => void }; export const pendingResolve = <T>() => { const container = {} as any; container.p = new Promise((r, j) => ([container.r, container.j] = [r, j])); [container.p.resolve, container.p.reject] = [container.r, container.j]; return container.p as PendingPromise<T>; };
使用
const pending = pendingResolve<Date>(); (async () => console.log(await pending) )(); pending.resolve(new Date("2020-01-01")); // Wed Jan 01 2020 08:00:00 GMT+0800 (中国标准时间)