Skip to content

Instantly share code, notes, and snippets.

@igorvolnyi
Forked from loilo/deepAsync.js
Last active May 29, 2019 12:19
Show Gist options
  • Save igorvolnyi/95b722d372e5f42dd2280a3d60065710 to your computer and use it in GitHub Desktop.
Save igorvolnyi/95b722d372e5f42dd2280a3d60065710 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 (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
}
}
@igorvolnyi
Copy link
Author

Change sort of deprecated typeof to instanceof.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment