Skip to content

Instantly share code, notes, and snippets.

@Goldziher
Last active November 27, 2021 19:21
Show Gist options
  • Save Goldziher/a63bf0063c6191e389c2753f06bbaa6b to your computer and use it in GitHub Desktop.
Save Goldziher/a63bf0063c6191e389c2753f06bbaa6b to your computer and use it in GitHub Desktop.
Recursive Promise Resolve
function isRecord<T = any>(value: unknown): value is Record<string | symbol, T> {
return !!(value && typeof value === 'object');
}
function isPromise<T = unknown>(value: unknown): value is Promise<T> {
return isRecord(value) && Reflect.has(value, 'then');
}
async function recursiveResolve<T>(
parsedObject: Record<string, any>,
): Promise<T> {
const output = {};
for (const [key, value] of Object.entries(parsedObject)) {
const resolved: unknown = isPromise(value) ? await value : value;
if (isRecord(resolved)) {
Reflect.set(output, key, await recursiveResolve(resolved));
} else {
Reflect.set(output, key, resolved);
}
}
return output as T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment