在super()调用完成之前设置实例成员

时间:2019-01-25 12:51:40

标签: javascript typescript promise

我已经决定需要某种可取消的承诺,因此我尝试自己编写。但是,我一直无法在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();
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用局部变量-收集解析器函数:

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;
}