Created
January 28, 2018 17:24
-
-
Save jcsrb/c9fd5d2928b4341b120d6db375679095 to your computer and use it in GitHub Desktop.
Lodash's .mapValues but for async functions
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
const mapValuesAsync = (obj, asyncFn) => { | |
const keys = Object.keys(obj); | |
const promises = keys.map(k => { | |
return asyncFn(obj[k]).then(newValue => { | |
return {key: k, value: newValue}; | |
}); | |
}); | |
return Promise.all(promises).then(values => { | |
const newObj = {}; | |
values.forEach(v => { | |
newObj[v.key] = v.value; | |
}); | |
return newObj; | |
}); | |
}; |
Thanks!
Nice, Thank you :). I tried to make it a bit more readable. This is what I came up with:
async function mapValuesAsync(obj, asyncFn) {
const promises = Object.entries(obj).map(([ key, value ]) => {
return asyncFn(key, value).then(newValue => ({ [ key ]: newValue }));
});
return Promise.all(promises).then(result => _.assign(...result));
};
I suggest you my own version :
function mapValuesAsync(collection, asyncFn) => {
const promises = Object.entries(collection).map(([ key, value ], index) => {
return asyncFn(value, key, index, collection).then(resolved => [ key, resolved ]);
});
return Promise.all(promises).then(Object.fromEntries);
}
Nice!!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! I needed that!