1
0
Fork 0
js-utils/src/Async.ts

71 lines
1.4 KiB
TypeScript
Raw Normal View History

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.
2021-08-08 19:58:43 +00:00
*
* @public
2020-03-29 13:43:52 +00:00
*/
export function defer(ms: number): Promise<void> {
return new Promise((res, _rej) => {
setTimeout(() => {
res();
}, ms);
});
}
2021-08-08 19:58:43 +00:00
/**
* Resolve with the given value, after a set amount of time.
*
* @public
*/
export function deferValue<T>(ms: number, val: T): Promise<T> {
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
*
* @public
2020-03-29 13:43:52 +00:00
*/
export function timeout<T>(ms: number, inner: Promise<T>): Promise<T> {
const limit = new Promise<T>((_res, rej) => {
2020-03-29 13:43:52 +00:00
setTimeout(() => {
rej(new TimeoutError());
}, ms);
});
return Promise.race([limit, inner]);
2020-03-29 13:43:52 +00:00
}
/**
2021-08-08 19:58:43 +00:00
* Resolve if `cb` returns true within `max` tries, otherwise reject with a `TimeoutError`.
*
* @public
* @throws TimeoutError
*/
2021-08-08 19:58:43 +00:00
export async function deferUntil(cb: PredicateC0, step: number, max: number): Promise<void> {
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;
}
count += 1;
2020-03-29 13:43:52 +00:00
}
throw new TimeoutError();
}
/**
* @public
* @deprecated
*/
export async function waitFor(cb: PredicateC0, step: number, tries: number): Promise<void> {
return deferUntil(cb, step, tries);
}