All files / src/lib async-utils.ts

100% Statements 16/16
75% Branches 3/4
100% Functions 6/6
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40              1x       60x 60x 58x   58x     57x     1x       5x     1x 2x 2x 2x 2x   1x          
/*
 * © Copyright 2022 HP Development Company, L.P.
 * SPDX-License-Identifier: MIT
 */
 
type Iterable<T, ReturnType> = (item: T, index: number) => Promise<ReturnType> | ReturnType;
 
export async function mapSeries<T = unknown, ReturnType = unknown>(
	data: T[],
	fn: Iterable<T, ReturnType>
): Promise<ReturnType[]> {
	const results = [];
	for (let index = 0; index < data.length; index++) {
		const item = data[index];
		// eslint-disable-next-line
		results.push(await fn(item, index));
	}
 
	return results;
}
 
export async function mapParallel<T = unknown, ReturnType = unknown>(
	data: T[],
	fn: Iterable<T, ReturnType>
): Promise<ReturnType[]> {
	return Promise.all(data.map((item, index) => fn(item, index)));
}
 
export async function nextTick<FN extends (...args: Array<unknown>) => any>(fn?: FN): Promise<ReturnType<FN>> {
	return new Promise((resolve, reject) => {
		process.nextTick(async () => {
			try {
				resolve(await fn?.());
			} catch (err) {
				reject(err);
			}
		});
	});
}