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-06 11:44:56 +02:00
|
|
|
export class Deferred<T = void> {
|
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() {
|
|
|
|
this.promise = new Promise<T>(resolve => {
|
|
|
|
this.resolve = resolve;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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
|
|
|
}
|
|
|
|
}
|