2018-06-19 14:23:48 +03:00
|
|
|
/**
|
|
|
|
* @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 23:28:31 +03:00
|
|
|
target.addEventListener(eventName, resolve, { once: true });
|
|
|
|
});
|
|
|
|
};
|
2018-06-19 14:23:48 +03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {!EventEmitter} emitter
|
|
|
|
* @param {string} eventName
|
|
|
|
* @return {!Promise<!Array>} With Event as the first item.
|
|
|
|
*/
|
|
|
|
const emittedOnce = (emitter, eventName) => {
|
2020-03-20 23:28:31 +03:00
|
|
|
return emittedNTimes(emitter, eventName, 1).then(([result]) => result);
|
|
|
|
};
|
2019-01-22 22:24:46 +03:00
|
|
|
|
|
|
|
const emittedNTimes = (emitter, eventName, times) => {
|
2020-03-20 23:28:31 +03:00
|
|
|
const events = [];
|
2018-06-19 14:23:48 +03:00
|
|
|
return new Promise(resolve => {
|
2019-01-22 22:24:46 +03:00
|
|
|
const handler = (...args) => {
|
2020-03-20 23:28:31 +03:00
|
|
|
events.push(args);
|
2019-01-22 22:24:46 +03:00
|
|
|
if (events.length === times) {
|
2020-03-20 23:28:31 +03:00
|
|
|
emitter.removeListener(eventName, handler);
|
|
|
|
resolve(events);
|
2019-01-22 22:24:46 +03:00
|
|
|
}
|
2020-03-20 23:28:31 +03:00
|
|
|
};
|
|
|
|
emitter.on(eventName, handler);
|
|
|
|
});
|
|
|
|
};
|
2018-06-19 14:23:48 +03:00
|
|
|
|
2020-03-20 23:28:31 +03:00
|
|
|
exports.emittedOnce = emittedOnce;
|
|
|
|
exports.emittedNTimes = emittedNTimes;
|
|
|
|
exports.waitForEvent = waitForEvent;
|