Last active
May 29, 2019 12:17
-
-
Save loilo/58df9f1f4ff994285a5969381ca2054f 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 (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