Recursively await a value

Example useage:

@stevekrouse.awaitAll(Promise.resolve({
  a: Promise.resolve([Promise.resolve(1)]),
}));

Returns:

{
  "a": [
    1
  ]
}
Readme
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
export async function awaitAll(value: any): Promise<any> {
function isPlainObject(value: any) {
return (typeof value === "object" && value !== null &&
value.constructor === Object);
}
async function innerResolve(value: any, stack: any[]): Promise<any> {
const resolved = await value;
if (stack.includes(resolved)) {
return resolved;
}
if (isPlainObject(resolved)) {
const keys = Object.keys(resolved);
const entries: [
string,
any,
][] = [];
for (const key of keys) {
const desc = Object.getOwnPropertyDescriptor(resolved, key);
if (!desc || desc.get)
continue;
entries.push([
key,
await innerResolve(resolved[key], stack.concat([resolved])),
]);
}
return Object.fromEntries(entries);
}
else if (Array.isArray(resolved)) {
// Recursively resolve array values.
return await Promise.all(resolved.map((val) => {
return innerResolve(val, stack.concat([resolved]));
}));
}
return resolved;
}
return innerResolve(value, []);
}
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.