node.js async.eachSeries太早调用最终回调

elm*_*lto 5 javascript asynchronous mongodb node.js

这就是我想要的:我有一个叫做结果的大数组.我希望将该数组中的每个项放入我的迭代函数中并将其保存到我的mongoDB中(我在这里省略了一些不重要的步骤).在将这些项目中的每一项保存到数据库(或拒绝)之后,我希望console.log显示"All done".不幸的是,所有完成都会在调用系列后立即显示,而其他所有内容仍在处理中.我该怎么做?

我正在使用mongoose和一个名为'light'的模型,为了便于阅读,我省略了代码中的所有错误消息.我对eachSeries部分使用node-async

var async = require('async');    
var results = [very big array]
var iteration = function(row,callbackDone) {
  light.find({data: row.data}, function (err,entry) {
    if(entry.length) {
      callbackDone();
      return console.log(entry + ' already exists');
    }
    var newEntry = new light(row);
    newEntry.save(function (err,doc) {
      console.log(entry + ' saved');
      callbackDone();
    });
  });
};

async.eachSeries(results,iteration, function (err) {
  console.log('All done');
});
Run Code Online (Sandbox Code Playgroud)

cla*_*lay 4

(答案,不是评论,因为文字太长了......)

我也在使用异步,你的问题让我困惑。我尝试了下面的代码,进一步得到了结果。这对我来说效果很好。(异步0.2.9)。甚至将我的超时延迟更改为 0。

唯一看起来奇怪的是if(entry.length)回调后打印的控制台信息。如果您收到很多“已经存在”的消息,我可能会看到它们稍后会出现 - 但这听起来不像您所描述的那样。

var async = require('async');  
var console = require('console');
var results = [ ];
results.push( {id:1,data:'a'} );
results.push( {id:2,data:'b'} );
results.push( {id:3,data:'c'} );
results.push( {id:4,data:'d'} );

function doFind( obj, callback ) {
  setTimeout( function() {
    console.log( "finding id=" + obj.data.id );
    obj.data.length = obj.data.id % 2;
    callback( null, obj.data );
  }, 500 );
}

function light( obj ) {
  this.id = obj.id;
  this.data = obj.data;
  this.save = function( callback ) {
    setTimeout( function() {
      console.log( "saving id=" + obj.id );
      callback( null, this );
    }, 500 );
  };
}

var iteration = function(row,callbackDone) {
  doFind({data: row}, function (err,entry) {
    if(entry.length) {
      callbackDone(); 
      return console.log( 'id=' + entry.id + ' already exists');
    }
    var newEntry = new light(row);
    newEntry.save(function (err,doc) {
      console.log( 'id=' + entry.id + ' saved');
      callbackDone();
    });
  });
};

async.eachSeries(results, iteration, function (err) {
  console.log('All done');
});
Run Code Online (Sandbox Code Playgroud)

结果

finding id=1
id=1 already exists
finding id=2
saving id=2
id=2 saved
finding id=3
id=3 already exists
finding id=4
saving id=4
id=4 saved
All done
Run Code Online (Sandbox Code Playgroud)