本文介绍了Lodash:是否可以将map与异步功能一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此代码

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

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

addEnabledProperty的作用是添加enabled属性来扩展对象,但这并不重要.该功能本身运行良好

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

是否可以使用_.map(或其他系统)来遍历整个responseJson数组以对每个元素使用addEnabledProperty?

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

我尝试过:

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

但是它没有使用异步,因此冻结了应用程序.

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

我尝试过:

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

但是我遇到了js错误(关于return await addEnabledProperty(chanell);行)

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

然后尝试

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

但是我有很多承诺...我不明白为什么...

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

还有什么!?

编辑:我理解您的抱怨,因为我没有指定addEnabledProperty()返回Promise,但是,实际上,我不知道.实际上,我写了"我有很多承诺...而且我不明白为什么"

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 "

推荐答案

要并行处理响应json,可以使用Promise.all:

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


由于addEnabledProperty方法是异步的,因此以下内容也应该起作用(每个@CRice):


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

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

这篇关于Lodash:是否可以将map与异步功能一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-10 13:36