자바스크립트 - 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
나는 이런 것이 필요해서, 그래서 이 미래 클래스를 만들었다:
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();
}
}
