javascript - async.filter is calling callback before all iterators finish - Stack Overflow

I am using caolan's async.js. I'm confused why the callback is getting called before all of t

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.

Share Improve this question edited Nov 2, 2015 at 20:16 Mrchief 76.3k20 gold badges145 silver badges192 bronze badges asked Jan 15, 2013 at 19:15 akronymnakronymn 2,4464 gold badges26 silver badges40 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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);

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信