0

So, I have an array of three objects. They have a name and a type property (and various others). I want to loop through each of them and use the readline module to get user input for all of them. Here's the javascript code I use to do this (using the async module):

async.each(questions.q, function (e, cb) {
  if (e.type === "s") {
    //not important
  } else if (e.type === "q") {
    rl.question(e.name, function (a) {
      //do stuff
      cb();
    });
  }
}, function (err) {
  if (err) throw err;
});

(question.q is the array of elements)

However, the output for all three of my objects with the type q is the following:

Question1Question2Question3 //input

Instead of doing one at a time, each prints all 3 out and then awaits an input. Why is this and how can I fix it?

kyr
  • 39
  • 6
  • Sounds like you shouldn't be running these asynchronously if you don't want this behavior but I suppose you could emulate a locking mechanism pretty easily with a numbered variable if you wanted to keep the code using async. – ShaneQful Sep 24 '14 at 21:47
  • @ShaneQful I thought running these asynchronously was the right thing to do? It waits until the stuff has been done and then moves on to the next one, right? – kyr Sep 24 '14 at 21:50
  • so you want them to run one at a time? try eachSeries – aembke Sep 24 '14 at 21:50
  • @kyr No running one at a time and moving on to the next is synchronous behavior. With asynchronous behavior they are running at the same time and order isn't guaranteed. – ShaneQful Sep 24 '14 at 21:52
  • @aembke That works! I'm surprised I didn't see that before. – kyr Sep 24 '14 at 21:53

1 Answers1

2

You can fix this by using async.eachSeries() instead of async.each(). async.each() iterates over the collection in parallel (you can limit the concurrency with async.eachLimit()), whereas async.eachSeries() iterates over the collection in series (one at a time).

mscdex
  • 104,356
  • 15
  • 192
  • 153