pulsar/spec/async-spec-helpers.js

46 lines
1.1 KiB
JavaScript
Raw Normal View History

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();
while (true) {
2019-05-31 19:33:56 +03:00
await timeoutPromise(100);
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;
}
if (Date.now() - startTime > 5000) {
2019-05-31 19:33:56 +03:00
throw new Error('Timed out waiting on ' + description);
}
}
}
2019-05-31 19:33:56 +03:00
function timeoutPromise(timeout) {
return new Promise(resolve => {
2019-05-31 19:33:56 +03:00
global.setTimeout(resolve, timeout);
});
}
2019-05-31 19:33:56 +03:00
function emitterEventPromise(emitter, event, timeout = 15000) {
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);
emitter.once(event, () => {
2019-05-31 19:33:56 +03:00
clearTimeout(timeoutHandle);
resolve();
});
});
2017-03-24 09:37:06 +03:00
}
2019-05-31 19:33:56 +03:00
exports.conditionPromise = conditionPromise;
exports.emitterEventPromise = emitterEventPromise;
exports.timeoutPromise = timeoutPromise;