javascript - node.js async.each() callback was called before all iteration was finished -


can explain me how can callback after iteration finished? used async.each function that:

async.each(products, function (product, callback) {     fs.appendfile('parselog.txt', "product name: " + product.name, function (err) {         console.log("iterate");         callback();     }); }, function (err) {     console.log("all finish"); }); 

so input looks like:

all finish  iterate  iterate iterate ... 

but expect "all finish" message prints after iteration. edit 1: sorry seems trouble in if(i > 10) return callback({ data: 'hi'}); // stop @ start of each loop. want exit after 11 iteration, stranges me why callback @ first.?

 async.each(products, function (product, callback) {     var = products.indexof(product);     if(i > 10)  return callback({ data: 'hi'}); // stop  fs.appendfile('parselog.txt', "product name: " + product.name, function (err) {             console.log("iterate");             callback();         }); .. 

you should limit number of products process before pass async.each:

async.each(products.slice(0, 11), function (product, callback) {   fs.appendfile('parselog.txt', "product name: " + product.name, function (err) {     console.log("iterate");     callback(err); // make sure pass `err`!   }); }, function(err) {   if (err) console.log('error', err);   console.log("all finish"); }); 

also, when call continuation callback, first argument "reserved" signal error occurred. in example, you're using pass object ({ data: 'hi' }) make async think error happened (unless intention?). proper idiom this:

callback(null, { data: 'hi' }) 

Comments