Skip to content

Instantly share code, notes, and snippets.

@jcsrb
Created January 28, 2018 17:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcsrb/c9fd5d2928b4341b120d6db375679095 to your computer and use it in GitHub Desktop.
Save jcsrb/c9fd5d2928b4341b120d6db375679095 to your computer and use it in GitHub Desktop.
Lodash's .mapValues but for async functions
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;
});
};
@rmoskal
Copy link

rmoskal commented Feb 19, 2020

Thanks! I needed that!

@JonathanTurnock
Copy link

Thanks!

@ClemensGrunewald
Copy link

ClemensGrunewald commented Jun 30, 2021

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));
};

@davidlandais
Copy link

davidlandais commented Sep 16, 2021

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);
  }

@Selenium39
Copy link

Nice!!!

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