【发布时间】:2015-10-27 05:59:45
【问题描述】:
async.waterfall 嵌套在 async.forEachOfLimit 循环中,如下面的代码所示。
问题:当代码在async.waterfall 中执行一个步骤时,如何跳过async.forEachLimit 的迭代?换句话说,突破async.waterfall 并回到async.forEachLimit。我已经在代码中注释了应该进行此检查的位置
当前代码报错Callback was already called.
另外,如果我想突破async.waterfall 时使用return callback() 代替cb(),则不会发生错误,但不会被跳过。
var async = require('async')
var users = ['a','b','c']
async.forEachOfLimit(users, 1, function(user, index, cb) {
console.log(index + ': ' + user)
async.waterfall([
function(callback) {
callback(null);
},
function(callback) {
// Skip async.forEAchOfLimit iteration when index == 1
if(index == 1)
cb()
callback(null);
}
], function (err, result) {
console.log(index + ": done")
cb()
});
}, function() {
console.log('ALL done')
})
错误
0: a
0: done
1: b
2: c
1: done
/Users/x/test/node_modules/async/lib/async.js:43
if (fn === null) throw new Error("Callback was already called.");
^
Error: Callback was already called.
期望的输出
0: a
0: done
1: b
2: c
2: done
ALL done
使用return callback()
var async = require('async')
var users = ['a','b','c']
async.forEachOfLimit(users, 1, function(user, index, cb) {
console.log(index + ': ' + user)
async.waterfall([
function(callback) {
callback(null);
},
function(callback) {
// Skip async.forEAchOfLimit iteration when index == 1
if(index == 1)
return callback()
callback(null);
}
], function (err, result) {
console.log(index + ": done")
cb()
});
}, function() {
console.log('ALL done')
})
输出
不会爆发...
0: a
0: done
1: b
1: done
2: c
2: done
ALL done
【问题讨论】:
-
你的意思是,就像一个正常循环中的
break?
标签: javascript node.js asynchronous