Async's each immediately prints out all elemen

2019-09-04 09:49发布

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?

1条回答
闹够了就滚
2楼-- · 2019-09-04 10:32

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).

查看更多
登录 后发表回答