electron/spec-main/events-helpers.ts

56 lines
1.6 KiB
TypeScript
Raw Normal View History

/**
* @fileoverview A set of helper functions to make it easier to work
* with events in async/await manner.
*/
/**
* @param {!EventTarget} target
* @param {string} eventName
* @return {!Promise<!Event>}
*/
export const waitForEvent = (target: EventTarget, eventName: string) => {
return new Promise(resolve => {
2020-03-20 20:28:31 +00:00
target.addEventListener(eventName, resolve, { once: true });
});
};
/**
* @param {!EventEmitter} emitter
* @param {string} eventName
* @return {!Promise<!Array>} With Event as the first item.
*/
export const emittedOnce = (emitter: NodeJS.EventEmitter, eventName: string, trigger?: () => void) => {
2020-03-20 20:28:31 +00:00
return emittedNTimes(emitter, eventName, 1, trigger).then(([result]) => result);
};
export const emittedNTimes = async (emitter: NodeJS.EventEmitter, eventName: string, times: number, trigger?: () => void) => {
2020-03-20 20:28:31 +00:00
const events: any[][] = [];
const p = new Promise<any[][]>(resolve => {
const handler = (...args: any[]) => {
2020-03-20 20:28:31 +00:00
events.push(args);
if (events.length === times) {
2020-03-20 20:28:31 +00:00
emitter.removeListener(eventName, handler);
resolve(events);
}
2020-03-20 20:28:31 +00:00
};
emitter.on(eventName, handler);
});
if (trigger) {
2020-03-20 20:28:31 +00:00
await Promise.resolve(trigger());
}
2020-03-20 20:28:31 +00:00
return p;
};
export const emittedUntil = async (emitter: NodeJS.EventEmitter, eventName: string, untilFn: Function) => {
const p = new Promise<any[][]>(resolve => {
const handler = (...args: any[]) => {
if (untilFn(...args)) {
2020-03-20 20:28:31 +00:00
emitter.removeListener(eventName, handler);
resolve(args);
}
2020-03-20 20:28:31 +00:00
};
emitter.on(eventName, handler);
});
return p;
};