Lodash:是否可以使用具有异步功能的地图?

rea*_*ebo 14 javascript async-await lodash

考虑这段代码

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

responseJson[0] = await addEnabledProperty(responseJson[0]);
Run Code Online (Sandbox Code Playgroud)

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 });
}
Run Code Online (Sandbox Code Playgroud)

有没有办法使用_.map(或另一个系统)循环通过整个responseJson数组来addEnabledProperty对每个元素使用?

我试过了:

responseJson = _.map(responseJson,  function(channel) {
            return addEnabledProperty(channell);
        });
Run Code Online (Sandbox Code Playgroud)

但它没有使用异步,所以它冻结了应用程序.

我试过了:

responseJson = _.map(responseJson,  function(channel) {
            return await addEnabledProperty(chanell);
        });
Run Code Online (Sandbox Code Playgroud)

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

等待是一个保留字

然后试过

responseJson = _.map(responseJson, async function(channel) {
            return await addEnabledProperty(channell);
        });
Run Code Online (Sandbox Code Playgroud)

但我得到了一系列的承诺......我不明白为什么......

还有什么!??

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

dhi*_*ilt 33

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

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

let result = await Promise.all(_.map(responseJson, async (json) => 
  await addEnabledProperty(json))
);
Run Code Online (Sandbox Code Playgroud)

由于addEnabledProperty方法是异步的,因此以下也应该有效(每个@CRice):

let result = await Promise.all(_.map(responseJson, addEnabledProperty));
Run Code Online (Sandbox Code Playgroud)

  • 不需要 `async` 匿名函数。`(json) =&gt; addEnabledProperty(json)` 在功能上是相同的。另外,afaik,我们可以直接将该函数传递给地图,而无需包装器:`_.map(responseJson, addEnabledProperty)` (2认同)
  • @CRice _"不需要异步匿名函数."_如果OP期望返回`Promise`并且'await`被使用,如果在匿名箭头函数中没有使用`async`,`await`将导致错误 (2认同)
  • @Saitama它之所以有效,是因为您将一个返回 Promise 的函数(我们知道,因为您需要使用“await”)与另一个仍返回 Promise 的函数包装在一起。由于匿名异步箭头的唯一参数被传递给“addEnabledProperty”,因此我们可以非常确定您*不需要*需要包装它。如果“addEnabledProperty”接受第二个(或第三个)参数,我们不想被从“_.map”传递的内容污染,那么这是必要的。 (2认同)