Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 900
brineon Avatar asked Sep 11 '14 15:09

brineon


1 Answers

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
});
like image 132
Joe Frambach Avatar answered Oct 09 '22 15:10

Joe Frambach