electron/spec/events-helpers.js

43 lines
1.1 KiB
JavaScript
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>}
*/
const waitForEvent = (target, eventName) => {
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.
*/
const emittedOnce = (emitter, eventName) => {
2020-03-20 20:28:31 +00:00
return emittedNTimes(emitter, eventName, 1).then(([result]) => result);
};
const emittedNTimes = (emitter, eventName, times) => {
2020-03-20 20:28:31 +00:00
const events = [];
return new Promise(resolve => {
const handler = (...args) => {
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);
});
};
2020-03-20 20:28:31 +00:00
exports.emittedOnce = emittedOnce;
exports.emittedNTimes = emittedNTimes;
exports.waitForEvent = waitForEvent;