Last active
November 27, 2021 19:21
-
-
Save Goldziher/a63bf0063c6191e389c2753f06bbaa6b to your computer and use it in GitHub Desktop.
Recursive Promise Resolve
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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