如果过滤函数是异步的,如何使用lodash过滤列表
How to filter a list using lodash if the filter function is asynchronous
我对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。
相关文章:
- Angular:使用选择列表选择过滤代码中的对象
- 如何使用javascript过滤复杂的json对象
- 使用angularjs内置过滤器过滤代码中的特定属性
- 如何在重建URL后从URL中传递过滤值,目的是使用Angular2和Typescript实现无限滚动
- 如何在D3.js中绘制地图投影上的点,并使用范围滑块过滤数据
- 使用PHP通过HTML表单选项选择器过滤MYSQL结果
- 尝试过滤“;引号"基于'"类别“;使用流星&mongo
- 使用jquery grep过滤具有值数组的json对象
- 如何使用javascript、jquery或其他javascript框架过滤数据
- 过滤”;溢价;页面加载选项使用混合
- 使用jquery过滤逗号分隔的span文本
- 使用下拉列表过滤 ng 重复,而不复制下拉选项
- 在 JavaScript 中使用正则表达式从字符串中过滤出百分比
- 在解析时使用变量过滤数据
- 如何使用 AngularJs 过滤 JSON 数据
- 使用 ng 模型按键入(键,值)对过滤
- 剑道网格不允许我在使用自定义列模板时过滤列
- RegExp / Jquery / Isotope 按关键字搜索和过滤:不使用某些关键字组合,为什么
- 斑马条纹在动态过滤和使用jquery时失去位置:even
- 过滤功能:使用KO挣扎