Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active May 29, 2019 12:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save loilo/58df9f1f4ff994285a5969381ca2054f to your computer and use it in GitHub Desktop.
Save loilo/58df9f1f4ff994285a5969381ca2054f to your computer and use it in GitHub Desktop.
Deeply resolves all promises in a data structure
// 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 (typeof object === 'object' && String(object) === '[object Object]') {
return Object
.entries(object)
.reduce(async (carry, [ key, value ]) => {
return Object.assign({}, carry, { [key]: await deepAsync(value) })
}, {})
// Await promise values
} else if (typeof object === 'object' && typeof object.then === '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