I was in need of something similar to this, so I decided to create my own future class:
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;
}
}
To use it, follow these steps:
let future = new Future<string>();
// Perform tasks and then:
future.resolve("A_VALUE");
// or reject the future:
future.reject("MESSAGE");
You can also store the future instance, return it, and then resolve/reject at a later time:
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();
}
}