稍后在TypeScript中解析或拒绝Promise

时间:2016-11-01 08:42:46

标签: javascript angular typescript promise

在Angular2 / TypeScript项目中,在显示对话框时,系统会将一个Promise对象返回给调用者,该对象将在用户关闭对话框后解析。

Promise类接口不公开resolve()或reject()方法,因此我必须保存对这些方法的引用以便以后调用它们。

这看起来并不正确。还有更好的方法吗?

class Dialog {
    private resolve;
    private reject;

    show(): Promise<any> {
        var p = new Promise<any>((resolve, reject) => {
            //save method references for later use
            this.resolve = resolve;
            this.reject = reject;
        });
        return p;
    }

    close() {
        this.resolve();
    }
}

1 个答案:

答案 0 :(得分:4)

我需要这样的东西,所以我创建了这个未来的课程:

class Future<T> implements PromiseLike<T> {
    private promise: Promise<T>;
    private resolveFunction: (value?: T | PromiseLike<T>) => void;
    private rejectFunction: (reason?: any) => void;

    constructor(promise?: Promise<T>) {
        if (!(this instanceof Future)){
            return new Future(promise);
        }

        this.promise = promise || new Promise(this.promiseExecutor.bind(this));
    }

    public asPromise(): Promise<T> {
        return this.promise;
    }

    public then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Future<TResult>;
    public then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Future<TResult>;
    public then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => any): Future<TResult> {
        return new Future(this.promise.then(onfulfilled, onrejected));
    }

    public catch(onrejected?: (reason: any) => T | PromiseLike<T>): Future<T>;
    public catch(onrejected?: (reason: any) => void): Future<T>;
    public catch(onrejected?: (reason: any) => any): Future<T> {
        return new Future(this.promise.catch(onrejected));
    }

    public resolve(value?: T | PromiseLike<T>) {
        this.resolveFunction(value);
    }

    public reject(reason?: any) {
        this.rejectFunction(reason);
    }

    private promiseExecutor(resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) {
        this.resolveFunction = resolve;
        this.rejectFunction = reject;
    }
}

像这样使用它:

let future = new Future<string>();

// do what not and then:
future.resolve("A_VALUE");
// or reject it:
future.reject("MESSAGE");

您还可以保存将来的实例,将其返回,然后再解决/拒绝:

class MyClass {
    private future: Future<string[]>;

    constructor() {
        this.future = new Future<string[]>();
    }

    fetch(url: string): Promise<string[]> {
        ISSUE_HTTP_REQUEST(url)
            .then(this.future.resolve.bind(this.future))
            .catch(this.future.reject.bind(this.future));

        return this.future.asPromise();
    }
}