2019-05-31 19:33:56 +03:00
|
|
|
async function conditionPromise(
|
2019-02-22 10:55:17 +03:00
|
|
|
condition,
|
|
|
|
description = 'anonymous condition'
|
|
|
|
) {
|
2019-05-31 19:33:56 +03:00
|
|
|
const startTime = Date.now();
|
2016-08-12 18:46:11 +03:00
|
|
|
|
2016-09-21 02:52:47 +03:00
|
|
|
while (true) {
|
2019-05-31 19:33:56 +03:00
|
|
|
await timeoutPromise(100);
|
2016-09-21 02:52:47 +03:00
|
|
|
|
2020-09-17 01:36:54 +03:00
|
|
|
// if condition is sync
|
|
|
|
if (condition.constructor.name !== 'AsyncFunction' && condition()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// if condition is async
|
|
|
|
else if (await condition()) {
|
2019-05-31 19:33:56 +03:00
|
|
|
return;
|
2016-09-21 02:52:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (Date.now() - startTime > 5000) {
|
2019-05-31 19:33:56 +03:00
|
|
|
throw new Error('Timed out waiting on ' + description);
|
2016-09-21 02:52:47 +03:00
|
|
|
}
|
|
|
|
}
|
2016-08-12 18:46:11 +03:00
|
|
|
}
|
|
|
|
|
2019-05-31 19:33:56 +03:00
|
|
|
function timeoutPromise(timeout) {
|
2018-08-24 22:00:44 +03:00
|
|
|
return new Promise(resolve => {
|
2019-05-31 19:33:56 +03:00
|
|
|
global.setTimeout(resolve, timeout);
|
|
|
|
});
|
2016-08-12 18:46:12 +03:00
|
|
|
}
|
|
|
|
|
2019-05-31 19:33:56 +03:00
|
|
|
function emitterEventPromise(emitter, event, timeout = 15000) {
|
2017-04-07 23:20:44 +03:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const timeoutHandle = setTimeout(() => {
|
2019-05-31 19:33:56 +03:00
|
|
|
reject(new Error(`Timed out waiting for '${event}' event`));
|
|
|
|
}, timeout);
|
2017-04-07 23:20:44 +03:00
|
|
|
emitter.once(event, () => {
|
2019-05-31 19:33:56 +03:00
|
|
|
clearTimeout(timeoutHandle);
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
});
|
2017-03-24 09:37:06 +03:00
|
|
|
}
|
2017-06-20 22:44:05 +03:00
|
|
|
|
2019-05-31 19:33:56 +03:00
|
|
|
exports.conditionPromise = conditionPromise;
|
|
|
|
exports.emitterEventPromise = emitterEventPromise;
|
|
|
|
exports.timeoutPromise = timeoutPromise;
|