Skip to content

Instantly share code, notes, and snippets.

@latel
Created February 15, 2019 08:55
Show Gist options
  • Save latel/da6f050105be61f8a6156bd2796ecce6 to your computer and use it in GitHub Desktop.
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.
/**
* 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