-
-
Save igorvolnyi/95b722d372e5f42dd2280a3d60065710 to your computer and use it in GitHub Desktop.
Deeply resolves all promises in a data structure
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
// Arbitrarily nested object containing Promises goes in | |
// Plain data structure comes out | |
async function deepAsync (object) { | |
// Walk arrays | |
if (Array.isArray(object)) { | |
return Promise.all(object.map(async item => await deepAsync(item))) | |
// Walk objects | |
} else if (object instanceof Object) { | |
return Object | |
.entries(object) | |
.reduce(async (carry, [ key, value ]) => { | |
return Object.assign({}, carry, { [key]: await deepAsync(value) }) | |
}, {}) | |
// Await promise values | |
} else if (object instanceof Object && typeof object.then instanceof Function) { | |
return deepAsync(await object) | |
// Return all others | |
} else { | |
return object | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Change sort of deprecated typeof to instanceof.