2022-10-08 19:10:17 +00:00
|
|
|
import { TimeoutError } from './error/TimeoutError.js';
|
|
|
|
import { PredicateC0 } from './Predicate.js';
|
2020-03-29 13:43:52 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Resolve after a set amount of time.
|
2021-08-08 19:58:43 +00:00
|
|
|
*
|
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);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-08-08 19:58:43 +00:00
|
|
|
/**
|
|
|
|
* Resolve with the given value, after a set amount of time.
|
|
|
|
*
|
|
|
|
* @public
|
|
|
|
*/
|
2020-12-29 05:24:46 +00:00
|
|
|
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.
|
2021-08-08 19:58:43 +00:00
|
|
|
*
|
2020-03-31 13:49:18 +00:00
|
|
|
* @public
|
2020-03-29 13:43:52 +00:00
|
|
|
*/
|
2021-08-08 00:34:19 +00:00
|
|
|
export function timeout<T>(ms: number, inner: 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);
|
|
|
|
});
|
|
|
|
|
2021-08-08 00:34:19 +00:00
|
|
|
return Promise.race([limit, inner]);
|
2020-03-29 13:43:52 +00:00
|
|
|
}
|
|
|
|
|
2020-03-31 13:49:18 +00:00
|
|
|
/**
|
2021-08-08 19:58:43 +00:00
|
|
|
* Resolve if `cb` returns true within `max` tries, otherwise reject with a `TimeoutError`.
|
|
|
|
*
|
2020-03-31 13:49:18 +00:00
|
|
|
* @public
|
|
|
|
* @throws TimeoutError
|
|
|
|
*/
|
2021-08-08 19:58:43 +00:00
|
|
|
export async function deferUntil(cb: PredicateC0, step: number, max: number): Promise<void> {
|
2021-08-08 00:34:19 +00:00
|
|
|
let count = 0;
|
2021-08-08 19:58:43 +00:00
|
|
|
while (count < max) {
|
2020-03-29 13:43:52 +00:00
|
|
|
await defer(step);
|
|
|
|
if (cb()) {
|
|
|
|
return;
|
|
|
|
}
|
2021-08-08 00:34:19 +00:00
|
|
|
count += 1;
|
2020-03-29 13:43:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new TimeoutError();
|
|
|
|
}
|
2021-08-08 00:34:19 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @public
|
|
|
|
* @deprecated
|
|
|
|
*/
|
|
|
|
export async function waitFor(cb: PredicateC0, step: number, tries: number): Promise<void> {
|
|
|
|
return deferUntil(cb, step, tries);
|
|
|
|
}
|