Reputation: 123
I am new to lodash and Javascript in general. I am using nodejs. I am using the lodash filter function to filter some contents in my collection.
Here is the snippet
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.
});
My question is, how do I do this? using a closure? Is it possible to do this within the lodash filter function? Thanks in advance.
Upvotes: 12
Views: 9212
Reputation: 4901
If you want to accomplish this with lodash instead of installing a new library(async
) you can do the following:
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)
Upvotes: 1
Reputation: 627
Lodash isn't an asyncronous tool. It makes filtering information in realtime veery fast. When you need to make a process asynchronous, you must use bluebird, Async, Native promises or callbacks.
I think that you should use Lodash and Underscore, only to organize Objectdata in realtime.
Upvotes: 0
Reputation: 27247
lodash may not be the best tool for this job. I recommend you use async
.
https://github.com/caolan/async#filter
Example: fs.exists
is an asynchronous function which checks for the existence of a file then calls a callback.
async.filter(['file1','file2','file3'], fs.exists, function(results){
// results now equals an array of the existing files
});
Upvotes: 6