electron/spec-main/events-helpers.ts
Samuel Attard a96b6e2c96 build: move to the new docs parser (#18103)
* build: move to the new docs parser

* chore: remove the bad getTitle param doc

* build: update parser/ts gen deps + fix some docs issues highlighted by GH desktop

* chore: apply suggestions from code review

Co-Authored-By: MarshallOfSound <samuel.r.attard@gmail.com>

* chore: update docs for accidentally removed things

* chore: update docs/api/command-line.md

Co-Authored-By: MarshallOfSound <samuel.r.attard@gmail.com>
2019-05-06 08:29:01 -07:00

38 lines
1.1 KiB
TypeScript

/**
* @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 => {
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) => {
return emittedNTimes(emitter, eventName, 1).then(([result]) => result)
}
export const emittedNTimes = (emitter: NodeJS.EventEmitter, eventName: string, times: number) => {
const events: any[][] = []
return new Promise<any[][]>(resolve => {
const handler = (...args: any[]) => {
events.push(args)
if (events.length === times) {
emitter.removeListener(eventName, handler)
resolve(events)
}
}
emitter.on(eventName, handler)
})
}