async.each() 最终回调未执行

async.each() final callback is not executed

async.each(spiders, function(){
    console.log('hi');
}, function(err) {
    if(err) { console.log(err);}
    else console.log('ok');
});

记录 'hi' 后,异步未执行回调并记录 'ok' 或错误。

我的代码有什么问题?

引自 async.each 文档:

iterator(item, callback) - A function to apply to each item in arr. The iterator is passed a callback(err) which must be called once it has completed. If no error has occurred, the callback should be run without arguments or with an explicit null argument.

结论:你忘了带回调参数,所以也没调用。

async 为您的 iterator 函数提供了两个重要参数:itemcallback。第一个给你数组中的实际数据项,第二个是一个函数,表示实际方法的结束。当每个迭代器调用都指示自己的回调时,将调用最终回调(带有 log('ok') 的回调。

所以你的代码应该是这样的:

async.each(spiders, function(item, callback) {
  console.log('spider: ' + item);
  callback(null);
}, function(err) {
  if (err) {
    return console.log(err);
  }
  console.log('ok');
});

null参数表示没有错误

另请注意,这样处理错误是一种更好的做法。