如果过滤函数是异步的,如何使用lodash过滤列表

How to filter a list using lodash if the filter function is asynchronous

本文关键字:过滤 何使用 列表 lodash 函数 异步 如果      更新时间:2023-09-26

我对lodash和Javascript一般来说都是新手。我正在使用nodejs。我正在使用lodash过滤器功能来过滤我收藏的一些内容。

这是的片段

filteredrows = _.filter(rows, function(row, index){
   //here I need to call some asynchronous function which checks the row
   //the return value of this asynchronous function will determine whether to return true or false for the filter function.
});

我的问题是,我该怎么做?使用封口?是否可以在lodash过滤器功能范围内进行此操作?提前谢谢。

lodash可能不是这项工作的最佳工具。我建议您使用async

https://github.com/caolan/async#filter

示例:fs.exists是一个异步函数,它检查文件是否存在,然后调用回调。

async.filter(['file1','file2','file3'], fs.exists, function(results){
    // results now equals an array of the existing files
});

如果你想用lodash而不是安装一个新的库(async)来实现这一点,你可以执行以下操作:

const rowFilterPredicate = async (row, index) => {
  // here I need to call some asynchronous function which checks the row
  // the return value of this asynchronous function will determine whether to return true or false for the filter function.
}
// First use Promise.all to get the resolved result of your predicate
const filterPredicateResults = await Promise.all(_.map(rows, rowFilterPredicate));
filteredrows = _.chain(rows)
  .zip(filterPredicateResults) // match those predicate results to the rows
  .filter(1) // filter based on the predicate results
  .map(0) // map to just the row values
  .value(); // get the result of the chain (filtered array of rows)

Lodash不是一个异步工具。它使得实时过滤信息的速度变快。当您需要使进程异步时,必须使用bluebird、Async、Native promise或回调。

我认为您应该使用Lodash和Undercore,只是为了实时组织Objectdata。