wallet-core: simplify/optimize async condition
This commit is contained in:
parent
f9d1c4a89e
commit
8c670bd06d
@ -23,6 +23,8 @@ export interface OpenedPromise<T> {
|
|||||||
/**
|
/**
|
||||||
* Get an unresolved promise together with its extracted resolve / reject
|
* Get an unresolved promise together with its extracted resolve / reject
|
||||||
* function.
|
* function.
|
||||||
|
*
|
||||||
|
* Recent ECMAScript proposals also call this a promise capability.
|
||||||
*/
|
*/
|
||||||
export function openPromise<T>(): OpenedPromise<T> {
|
export function openPromise<T>(): OpenedPromise<T> {
|
||||||
let resolve: ((x?: any) => void) | null = null;
|
let resolve: ((x?: any) => void) | null = null;
|
||||||
@ -39,22 +41,20 @@ export function openPromise<T>(): OpenedPromise<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class AsyncCondition {
|
export class AsyncCondition {
|
||||||
private _waitPromise: Promise<void>;
|
private promCap?: OpenedPromise<void> = undefined;
|
||||||
private _resolveWaitPromise: (val: void) => void;
|
constructor() {}
|
||||||
constructor() {
|
|
||||||
const op = openPromise<void>();
|
|
||||||
this._waitPromise = op.promise;
|
|
||||||
this._resolveWaitPromise = op.resolve;
|
|
||||||
}
|
|
||||||
|
|
||||||
wait(): Promise<void> {
|
wait(): Promise<void> {
|
||||||
return this._waitPromise;
|
if (!this.promCap) {
|
||||||
|
this.promCap = openPromise<void>();
|
||||||
|
}
|
||||||
|
return this.promCap.promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
trigger(): void {
|
trigger(): void {
|
||||||
this._resolveWaitPromise();
|
if (this.promCap) {
|
||||||
const op = openPromise<void>();
|
this.promCap.resolve();
|
||||||
this._waitPromise = op.promise;
|
}
|
||||||
this._resolveWaitPromise = op.resolve;
|
this.promCap = undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user