summaryrefslogtreecommitdiff
path: root/src/prelude/await-all.ts
blob: 24795f3ae5f9c06fca477329112d850faa353ff3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
type Await<T> = T extends Promise<infer U> ? U : T;

type AwaitAll<T> = {
	[P in keyof T]: Await<T[P]>;
};

export async function awaitAll<T>(obj: T): Promise<AwaitAll<T>> {
	const target = {} as any;
	const keys = Object.keys(obj);
	const values = Object.values(obj);

	const resolvedValues = await Promise.all(values.map(value =>
		(!value || !value.constructor || value.constructor.name !== 'Object')
			? value
			: awaitAll(value)
	));

	for (let i = 0; i < keys.length; i++) {
		target[keys[i]] = resolvedValues[i];
	}

	return target;
}