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

后端 未结 4 1128
孤街浪徒
孤街浪徒 2021-02-12 13:10

Consider this code

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


        
相关标签:
4条回答
  • 2021-02-12 13:13

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

    It cover both promise and normal pattern by same code.

    _p.map([1, 2, 3], async (v) => await promiseFunction());
    
    0 讨论(0)
  • 2021-02-12 13:17

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

    responseJson = await Promise.all(_.map(responseJson, (channel) => {
            return addEnabledProperty(channel);
        }));
    
    0 讨论(0)
  • 2021-02-12 13:18

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

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

    const responseJson = await Promise.all( _
                           .chain( response.json() )
                           .sortBy( 'number' )
                           .map( json => addEnabledProperty( json ) )
                           .value()
                         )
    
    0 讨论(0)
  • 2021-02-12 13:32

    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));
    
    0 讨论(0)
提交回复
热议问题