异步的每个立即打印出所有元素 [英] Async's each immediately prints out all elements

查看:64
本文介绍了异步的每个立即打印出所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个包含三个对象的数组.它们具有名称和类型属性(以及其他各种属性).我想遍历它们中的每一个,并使用readline模块来获取所有它们的用户输入.这是我用来执行此操作的javascript代码(使用async模块):

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是元素数组)

但是,使用type q的所有三个对象的输出如下:

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

Question1Question2Question3 //input

each而不是一次执行所有操作,而是打印出全部3个,然后等待输入.为什么会这样,我该如何解决?

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?

推荐答案

您可以通过使用async.eachSeries()而不是async.each()来解决此问题. async.each()并行遍历集合(您可以使用async.eachLimit()限制并发性),而async.eachSeries()串行遍历集合(一次一个).

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

这篇关于异步的每个立即打印出所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆