Reputation: 2446
I am using caolan's async.js. I'm confused why the callback is getting called before all of the iterators are done. When I run the following code:
async.filter(matched_objects.fields, function(item, callback) {
console.log('checking field: ' + item.id);
if(item.id == 130 || item.id == 131) {
console.log('calling field true: ' + item.id);
callback(true);
}
callback(false);
},
function(fieldResults) {
console.log('fieldsResults.length=' + fieldResults.length);
});
I get the following output:
checking field: 130
calling field true: 130
fieldsResults.length=1
checking field: 131
calling field true: 131
It doesn't make any sense to me that the console.log in the callback is getting called before the second results.fields
item is checked in the filter loop.
Upvotes: 1
Views: 3975
Reputation: 76228
The problem is the callback(false)
is called everytime, even if you hit the if
condition. The right approach would be to add a return
statement:
if(item.id == 130 || item.id == 131) {
console.log('calling field true: ' + item.id);
return callback(true); // now you won't call callback(false) everytime
}
callback(false);
And you can even shorten the filter by saying:
callback(item.id == 130 || item.id == 131);
Upvotes: 6
Reputation: 2446
After more experimentation I've discovered the problem was the callback(false); line. apparently this caused the filter to exit. I guess this makes sense since it forces the callback to be called.
Upvotes: 0