Async: Async.each does not stop when an iterator returns an error

Created on 8 Apr 2013  路  2Comments  路  Source: caolan/async

Why does this loop not stop iterating when the value reaches 666?

Async = require('async');
var arr = [];


for(var x = 0; x < 1000; x++){
    arr.push(x);
}

Async.each(arr, 
    function(i, cb){

        console.log(i);
        if(i >= 666){
            cb('EVIL');
        } else {
            cb(null);
        }

    }, function(err){

        if(err){
            console.log('Async is ' + err);
        } else {
            console.log('Async loves you');
        }

    }
);

Most helpful comment

Because it's not iterating over a loop, it's invoking the iterator function once for each element of the Array. The iterator is invoked on all elements of the Array asynchronously. If one calls back with an error, the final callback is called, but that doesn't stop (and can't stop) the other iterators from working.

If you want something which will iterate through the array sequentially, stopping if it gets an error, use eachSeries.

All 2 comments

Because it's not iterating over a loop, it's invoking the iterator function once for each element of the Array. The iterator is invoked on all elements of the Array asynchronously. If one calls back with an error, the final callback is called, but that doesn't stop (and can't stop) the other iterators from working.

If you want something which will iterate through the array sequentially, stopping if it gets an error, use eachSeries.

Thanks for info Brian.

Was this page helpful?
0 / 5 - 0 ratings