Skip to content
Advertisement

Lodash: is it possible to use map with async functions?

Consider this code

const response  = await fetch('<my url>');
const responseJson = await response.json();
responseJson =  _.sortBy(responseJson, "number");

responseJson[0] = await addEnabledProperty(responseJson[0]);

What addEnabledProperty does is to extend the object adding an enabled property, but this is not important. The function itself works well

async function addEnabledProperty (channel){

    const channelId = channel.id;
    const stored_status = await AsyncStorage.getItem(`ChannelIsEnabled:${channelId}`);
    let boolean_status = false;
    if (stored_status == null) {
        boolean_status = true;
    } else {
        boolean_status = (stored_status == 'true');
    }

    return _.extend({}, channel, { enabled: boolean_status });
}

Is there a way to use _.map (or another system), to loop trough entire responseJson array to use addEnabledProperty against each element?

I tried:

responseJson = _.map(responseJson,  function(channel) {
            return addEnabledProperty(channell);
        });

But it’s not using async so it freeze the app.

I tried:

responseJson = _.map(responseJson,  function(channel) {
            return await addEnabledProperty(chanell);
        });

But i got a js error (about the row return await addEnabledProperty(chanell);)

await is a reserved word

Then tried

responseJson = _.map(responseJson, async function(channel) {
            return await addEnabledProperty(channell);
        });

But I got an array of Promises… and I don’t understand why…

What else!??

EDIT: I understand your complains about I didn’t specify that addEnabledProperty() returns a Promise, but, really, I didn’t know it. In fact, I wrote “I got an array of Promises… and I don’t understand why

Advertisement

Answer

To process your response jsons in parallel you may use Promise.all:

const responseJson = await response.json();
responseJson = _.sortBy(responseJson, "number");

let result = await Promise.all(_.map(responseJson, async (json) => 
  await addEnabledProperty(json))
);

Since addEnabledProperty method is async, the following also should work (per @CRice):

let result = await Promise.all(_.map(responseJson, addEnabledProperty));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement