我决定我需要某种可取消的承诺,所以我尝试自己写。但是,我一直无法在super()调用完成之前设置实例成员-为了扩展Promise,可能需要在super()之前设置一些内容。
所以,我的问题是:有没有一种简单的方法可以在不重写Promise功能的情况下实现这一目标?
export class CancelablePromise<T> extends Promise<T> {
private onCancel: () => void = () => {};
public constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void, oncancel: (handler: ()=>void)=>void) => void) {
super( (res, rej) => {
executor(res, rej, ( handler: () => void) => { this.onCancel = handler ; });
});
}
public Cancel(): void {
this.onCancel();
}
}
最佳答案
您可以使用局部变量-收集解析器函数:
constructor(executor) {
let resolve, reject;
super((res, rej) => { resolve = res; reject = rej; });
try {
executor(resolve, reject, handler => { this.onCancel = handler ; });
} catch(e) {
reject(e);
}
}
或在创建属性之前存储处理程序:
constructor(executor) {
let onCancel; // = default handler
super((resolve, reject) => {
executor(resolve, reject, handler => { onCancel = handler; });
});
this.onCancel = onCancel;
}