callum
callum

Reputation: 37819

Why does async.filter() not accept an error?

The docs for async.filter() say the iterator callback does NOT accept an error, apparently "in line with the way node libraries work with truth tests like fs.exists".

I don't understand that explanation at all. Why can't it accept errors? What if my asynchronous truth test involves doing something that might result in error sometimes?

Example: I have an array of path names that could be a mixture of files or directories. I want to filter out the directories, so I use async.filter with an iterator that calls fs.stat on them, and then calls done(stat.isFile());. But what if my fs.stat hits an ENOENT error for one of the paths? What do I do with that error?

Upvotes: 1

Views: 418

Answers (1)

clay
clay

Reputation: 6017

The async.filter() method, just like the .some() and .every() methods, are merely checking for true or false against each item in the array. These is not meant for control-flow to catch errors, and potentially not meant for large processing at each step. The author of async leaves that up to you though, and if one of your checks throws an error, that could be interpreted as a false.

An alternative for you, if you require every path name to be valid, would be .each()

var filteredArray = [];
async.each( paths, function( path, eachCb ){
  //some asynchronous check you define
  checkpath( path, function( err ) {
    if( err ) return eachCb( err );
    filteredArray.push( path );
    eachCb( null );
  } );
}, function( eachErr ) {
    if( eachErr ) {
      console.log( "Not all paths were correct. " + eachErr.message );
      //other stuff here, perhaps a callback with this error message
    }
    else {
      //success!
      //filteredArray now filled with only valid paths, and only get here if no errors.
    }
} );

Upvotes: 1

Related Questions