Lodash: is it possible to use a card with asynchronous 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 it addEnabledPropertydoes is an extension of the object adding the property enabled, but that doesn't matter. 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 the entire responseJson array to use addEnabledPropertyfor each element?

I tried:

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

But he does not use async to freeze the application.

I tried:

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

But I got js error (about line return await addEnabledProperty(chanell);)

Waiting is a reserved word

Then tried

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

But I have an array of Promises ... and I don't understand why ...

What else!??

. , , , addEnabledProperty() Promise, , , . , " Promises... , "

+10
4

jsons Promise.all:

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

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

addEnabledProperty , ( @CRice):

let result = await Promise.all(_.map(responseJson, addEnabledProperty));
+24

Promise.all() .

responseJson = await Promise.all(_.map(responseJson, (channel) => {
        return addEnabledProperty(channel);
    }));
0

, async/await Promise.all.

lodash (_.chain) :

const responseJson = await Promise.all( _
                       .chain( response.json() )
                       .sortBy( 'number' )
                       .map( json => addEnabledProperty( json ) )
                       .value()
                     )
0

How about using part.js ( https://github.com/marpple/partial.js )

This covers both the promise and the normal pattern with the same code.

_p.map([1, 2, 3], async (v) => await promiseFunction());
0
source

Source: https://habr.com/ru/post/1688557/


All Articles