forked from electron/electron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevents-helpers.js
42 lines (38 loc) · 1.06 KB
/
events-helpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* @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>}
*/
const waitForEvent = (target, eventName) => {
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.
*/
const emittedOnce = (emitter, eventName) => {
return emittedNTimes(emitter, eventName, 1).then(([result]) => result);
};
const emittedNTimes = (emitter, eventName, times) => {
const events = [];
return new Promise(resolve => {
const handler = (...args) => {
events.push(args);
if (events.length === times) {
emitter.removeListener(eventName, handler);
resolve(events);
}
};
emitter.on(eventName, handler);
});
};
exports.emittedOnce = emittedOnce;
exports.emittedNTimes = emittedNTimes;
exports.waitForEvent = waitForEvent;