/** * Wraps a Promise with a timeout, rejecing the promise with the timeout. */ export function withTimeout( promise: Promise | void, message: string, timeout: number, ): Promise { return new Promise((resolve, reject) => { if (!(promise instanceof Promise)) { (resolve as any)(); return; } const timeoutId = setTimeout(() => { reject(new Error(message)); }, timeout); promise .then(val => { resolve(val); }) .catch(err => { reject(err); }) .finally(() => { clearTimeout(timeoutId); }); }); } /** * Iterates iterable, executes each function in parallel and awaits * all function return values */ export async function forEachAsync( it: Iterable, fn: (t: T) => void | Promise, ): Promise { const result: (void | Promise)[] = []; for (const e of it) { result.push(fn(e)); } await Promise.all(result); } /** * Iterates iterable, executes each function in parallel and awaits * all function return values returning the awaited result */ export function mapAsync(it: Iterable, fn: (t: T) => R | Promise): Promise { const result: (R | Promise)[] = []; for (const e of it) { result.push(fn(e)); } return Promise.all(result); }