2020-03-31 13:29:47 +00:00
|
|
|
import { TimeoutError } from './error/TimeoutError';
|
2020-03-31 22:38:25 +00:00
|
|
|
import { PredicateC0 } from './Predicate';
|
2020-03-29 13:43:52 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Resolve after a set amount of time.
|
2020-03-31 13:49:18 +00:00
|
|
|
* @public
|
2020-03-29 13:43:52 +00:00
|
|
|
*/
|
2020-12-29 05:24:46 +00:00
|
|
|
export function defer(ms: number): Promise<void> {
|
2021-07-10 22:32:47 +00:00
|
|
|
return new Promise((res, _rej) => {
|
2020-12-29 05:24:46 +00:00
|
|
|
setTimeout(() => {
|
|
|
|
res();
|
|
|
|
}, ms);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function deferValue<T>(ms: number, val: T): Promise<T> {
|
2021-07-10 22:32:47 +00:00
|
|
|
return new Promise((res, _rej) => {
|
2020-03-29 13:43:52 +00:00
|
|
|
setTimeout(() => {
|
|
|
|
res(val);
|
|
|
|
}, ms);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Reject after a set amount of time if the original promise has not yet resolved.
|
2020-03-31 13:49:18 +00:00
|
|
|
* @public
|
2020-03-29 13:43:52 +00:00
|
|
|
*/
|
|
|
|
export function timeout<T>(ms: number, oper: Promise<T>): Promise<T> {
|
2021-07-10 22:32:47 +00:00
|
|
|
const limit = new Promise<T>((_res, rej) => {
|
2020-03-29 13:43:52 +00:00
|
|
|
setTimeout(() => {
|
|
|
|
rej(new TimeoutError());
|
|
|
|
}, ms);
|
|
|
|
});
|
|
|
|
|
|
|
|
return Promise.race([limit, oper]);
|
|
|
|
}
|
|
|
|
|
2020-03-31 13:49:18 +00:00
|
|
|
/**
|
|
|
|
* Reject after a set number of attempts if the given predicate does not return true.
|
|
|
|
* @public
|
|
|
|
* @throws TimeoutError
|
|
|
|
*/
|
2020-03-31 02:31:51 +00:00
|
|
|
export async function waitFor(cb: PredicateC0, step: number, count: number): Promise<void> {
|
2020-03-29 13:43:52 +00:00
|
|
|
let accum = 0;
|
|
|
|
while (accum < count) {
|
|
|
|
await defer(step);
|
|
|
|
if (cb()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
accum += 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new TimeoutError();
|
|
|
|
}
|