2019-04-23 13:23:18 +02:00
|
|
|
/**
|
|
|
|
* Helper class to asynchronously wait until certain promises are resolved
|
|
|
|
*
|
|
|
|
* @example
|
|
|
|
* ```ts
|
|
|
|
* // myService
|
|
|
|
* private loaded: Deferred<void> = new Deferred();
|
|
|
|
* // after something was done
|
|
|
|
* this.loaded.resolve();
|
|
|
|
*
|
|
|
|
* // myOtherService or myComponent
|
|
|
|
* await this.myService.loaded;
|
|
|
|
* //
|
|
|
|
* ```
|
|
|
|
*/
|
2019-05-07 16:25:39 +02:00
|
|
|
export class Deferred<T = void> extends Promise<T> {
|
2019-04-23 13:23:18 +02:00
|
|
|
/**
|
|
|
|
* The promise to wait for
|
|
|
|
*/
|
|
|
|
public readonly promise: Promise<T>;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* custom resolve function
|
|
|
|
*/
|
2019-05-06 11:44:56 +02:00
|
|
|
private _resolve: (val?: T) => void;
|
2019-04-23 13:23:18 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates the promise and overloads the resolve function
|
|
|
|
*/
|
|
|
|
public constructor() {
|
2019-05-07 16:25:39 +02:00
|
|
|
let preResolve: (val?: T) => void;
|
|
|
|
super(resolve => {
|
|
|
|
preResolve = resolve;
|
2019-04-23 13:23:18 +02:00
|
|
|
});
|
2019-05-07 16:25:39 +02:00
|
|
|
this._resolve = preResolve;
|
2019-04-23 13:23:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Entry point for the resolve function
|
|
|
|
*/
|
2019-05-06 11:44:56 +02:00
|
|
|
public resolve(val?: T): void {
|
|
|
|
this._resolve(val);
|
2019-04-23 13:23:18 +02:00
|
|
|
}
|
|
|
|
}
|