async.eachSeries in node.js
Asked Answered
O

2

14

I have a loop in node.js

for (var i in files){
    var all = fs.readdirsync("./0");
    async.eachSeries(all, function(item){
        check(item); 
   }
}

The check(item) has a callback to another function.

As I can see, the async.eachSeries doesn't execute synchronously. The loop continues to execute the other items, before the callback in the check() function is finish.

How do I make the loop wait until the iteration is finished (including the callback)?

Omentum answered 26/5, 2014 at 6:33 Comment(0)
T
11

Assuming check accepts a callback, we can use mapSeries to achieve that.

async.mapSeries(files, function(file, outerCB) {
  var all = fs.readdirsync("./0");
  async.mapSeries(all, function(item, cb){
      check(item, cb);
  }, outerCB);
}, function(err, results) {
  // This is called when everything's done
});
Troth answered 26/5, 2014 at 6:51 Comment(0)
D
9

Outer loop needs to be async also. One of the the methods is to use 2 eachSeries loops or outer loop can be in parallel (each) if the files don't have to be processed in series:

var async = require('async');

async.eachSeries(files, function(file, outCb) 
{
  var all = fs.readFileSync(file);

  async.eachSeries(all, function(item, inCb) 
  {
    check(item);
    inCb(null);  // inner callback
  }, 
  function(err) 
  {
    outCb(null);  // outer callback
  });
},
function(err) 
{
  console.log('all done!!!');
});
Doble answered 26/5, 2014 at 7:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.