javascript Lodash:是否可以将地图与异步功能一起使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47065444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:09:57  来源:igfitidea点击:

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

javascriptasync-awaitlodash

提问by realtebo

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 addEnabledPropertydoes is to extend the object adding an enabledproperty, but this is not important. The function itself works well

什么addEnabledProperty是扩展对象添加enabled属性,但这并不重要。该功能本身运行良好

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 addEnabledPropertyagainst each element?

有没有办法使用_.map(或其他系统)来循环遍历整个 responseJson 数组以addEnabledProperty针对每个元素使用?

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

但我有一个 js 错误(关于行return await addEnabledProperty(chanell);

await is a reserved word

await 是一个保留字

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...

但是我得到了一系列 Promises ......我不明白为什么......

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"

编辑:我理解你抱怨我没有指定addEnabledProperty()返回 a Promise,但是,真的,我不知道。事实上,我写了“我得到了一系列的承诺......但我不明白为什么

回答by dhilt

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

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

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

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


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

由于addEnabledProperty方法是异步的,以下也应该有效(根据@CRice):

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

回答by Rodrigo Leite

You can use Promise.all()to run all the promises in your array.

您可以使用Promise.all()来运行数组中的所有承诺。

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

回答by Javid Jamae

I found that I didn't have to put the async / await inside of the Promise.allwrapper.

我发现我不必将 async / await 放在Promise.all包装器中。

Using that knowledge, in conjunction with lodash chain (_.chain) could result in the following simplified version of the accepted answer:

使用这些知识,结合 lodash chain ( _.chain) 可能会产生以下已接受答案的简化版本:

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

回答by Juneho Nam

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

如何使用 partial.js( https://github.com/marpple/partial.js)

It cover both promise and normal pattern by same code.

它通过相同的代码涵盖了 promise 和 normal 模式。

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