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

12

我对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过滤函数内是否可能实现此功能? 提前致谢。


简单来说:如果调用函数期望同步函数,则可以使用异步函数。因此,现在您无法使用_.filter - Felix Kling
是的,使用 lodash 是不可能的。 - Bergi
3个回答

6

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

5
你正在执行异步操作!你的性能已经大打折扣了。 - Joe Frambach

1
如果您想使用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)

0

Lodash不是一个异步工具。它可以使实时信息过滤非常快速。当您需要使进程异步化时,必须使用bluebirdAsync,本机承诺或回调。

我认为您应该仅使用Lodash和Underscore来组织实时对象数据。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接