Created
February 15, 2019 08:55
-
-
Save latel/da6f050105be61f8a6156bd2796ecce6 to your computer and use it in GitHub Desktop.
Finds nested promises within the provided value/object and returns one promise that resolves when all nested promises are resolved.
This file contains hidden or 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
/** | |
* Finds nested promises within the provided value/object and returns one | |
* promise that resolves when all nested promises are resolved. | |
* @param value The value to promisify. | |
*/ | |
export const resolveNestedPromises = async <T>(value: T): Promise<T> => { | |
if (value instanceof Promise) return value; | |
if (value instanceof Array) { | |
const elements = value.map(entry => resolveNestedPromises(entry)); | |
return Promise.all(elements) as any; | |
} | |
if (typeof value === 'object' && value !== null) { | |
let result: any = {}; | |
for (const key of Object.keys(value)) { | |
const property = await resolveNestedPromises((value as any)[key]); | |
result[key] = property; | |
} | |
return result; | |
} | |
return value; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment