Node.jsasynchronouseachLimit如何在这种情况下工作?

我写了一个小async脚本来批量插入大量的JSON文件到MongoDB分片集群中。 这是我第一次使用这个模块(而且我还在学习Node.js)。 我不知道我是否做对了。

  • 该代码是瀑布(1)的最后一部分:以前的函数结束与dbcollfiles属性的对象。
  • files数组包含数百个文件path,并且应用于数组的每个元素的函数又是一个瀑布(2)。
  • 瀑布(2)由以下内容组成:读取,parsing,插入。 当这个瀑布结束时(3)我调用complete完成数组中单个项目的处理,传递错误(如果有的话)。

到目前为止这么好,对吗?

我不明白的是在async.eachLimitcallback(4)内发生了什么。 从文档:

在所有迭代器函数完成之后调用的callback,或发生错误。

也就是说,当所有函数完成后, next()调用(5)结束脚本。 但是,当按照文档发生单个错误时,会调用相同的callback函数(4)。 这是我的脚本停止时发生单个文件的失败。

我怎样才能避免这一点?

 async.waterfall([ // 1 // ... function (obj, next) { async.eachLimit(obj.files, 1000, function (file, complete) { async.waterfall([ // 2 function (next) { fs.readFile(file, {}, function (err, data) { next(err, data); }); }, function (data, next) { // Parse (assuming all well formed) next(null, JSON.parse(data)); }, function (doc, next) { // Insert obj.coll.insert(doc, {w: 1}, function (err, doc) { next(err); }); } ], function (err, result) { // 3 complete(err); }); }, function (err) { // 4 if (err) console.error(err); next(null, obj); // 5 } ); } ], function (err, obj) { // Waterfall end if (err) console.error(err); obj.db.close(); // Always close the connection }); 

如果你不想让它在出现错误的情况下中断,你应该用一个虚假的第一个参数来调用callback,就像这样(看看// 3)。 这跟你有关吗?我理解正确吗?

 async.waterfall([ // 1 // ... function (obj, next) { async.eachLimit(obj.files, 1000, function (file, complete) { async.waterfall([ // 2 function (next) { fs.readFile(file, {}, function (err, data) { next(err, data); }); }, function (data, next) { // Parse (assuming all well formed) next(null, JSON.parse(data)); }, function (doc, next) { // Insert obj.coll.insert(doc, {w: 1}, function (err, doc) { next(err); }); } ], function (err, result) { // 3 if (err) { console.log(file + ' threw an error'); console.log(err); console.log('proceeding with execution'); } complete(); }); }, function (err) { // 4 next(null, obj); // 5 } ); } ], function (err, obj) { // Waterfall end if (err) console.error(err); obj.db.close(); // Always close the connection });