How To Skip A "async.foreachof" Loop Iteration In Node.js
Solution 1:
In your first solution when index matches 1, cb
is called twice, that is why you keep getting Callback was already called
error. Although you call forEachOfLimit callback cb
, your code doesn't stop execution and calls callback. In callback function cb
is executed one more time.
varasync = 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 == 1if(index == 1)
cb() // First callback callcallback(null);
}
], function (err, result) {
console.log(index + ": done")
cb() // Second callback call
});
}, function() {
console.log('ALL done')
})
In second solution if index matches 1, it calls callback with no arguments and skips calling callback with null argument. Still doesn't break out of waterfall.
To solve your problem using waterfall you have two options.
Call waterfall's method callback with an error argument, which breaks out of waterfall and than handle this error in waterfall's callback.
varasync = 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 == 1if(index == 1) returncallback(newError('Index equals 1')); callback(null); } ], function (err, result) { console.log(index + ": done") if(err.message == 'Index equals 1') { err = null; // If you want to continue executing forEachOfLimit no error must be passed to cb } cb(err, result); }); }, function() { console.log('ALL done') });
In the beginning of each waterfalled method skip the rest of the code and call callback immediately (which is what you've done in second attempt)
varasync = 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 execution of the rest of waterfall method immediatelyif(index == 1) returncallback() // Some additional code herecallback(null); } ], function (err, result) { console.log(index + ": done") cb() }); }, function() { console.log('ALL done') })
Post a Comment for "How To Skip A "async.foreachof" Loop Iteration In Node.js"