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.
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.
2 Answers
Reset to default 6The 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);
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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745466864a4628952.html
评论列表(0条)