Last active
April 19, 2022 12:43
-
-
Save voxpelli/2c9b58e5fef9ed46a2cbfef21416d0e2 to your computer and use it in GitHub Desktop.
A recursive Promise.all() that works on objects
This file contains 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
const zipObject = function (keys, values) { | |
const result = {}; | |
keys.forEach((key, i) => { | |
result[key] = values[i]; | |
}); | |
return result; | |
}; | |
const recursiveObjectPromiseAll = function (obj) { | |
const keys = Object.keys(obj); | |
return Promise.all(keys.map(key => { | |
const value = obj[key]; | |
// Promise.resolve(value) !== value should work, but !value.then always works | |
if (typeof value === 'object' && !value.then) { | |
return recursiveObjectPromiseAll(value); | |
} | |
return value; | |
})) | |
.then(result => zipObject(keys, result)); | |
}; |
@hugogiraudel Good point!
Great gist. Thanks! 👍
Thanks, this is great - Promise.All should have always been recursive and worked to return the data in the same layout as it was provided.
shorter ;)
const zipObject = (keys = [], values = []) => keys.reduce((accumulator, key, index) => Object.assign(accumulator,{[key]: values[index]}),{});
I would probably author
zipObject
like this:const zipObject = (keys = [], values = []) => { return keys.reduce((accumulator, key, index) => { accumulator[key] = values[index] return accumulator }, {}) }:)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would probably author
zipObject
like this::)