【问题标题】:Understand JavaScript Synchronous vs Asynchronous [duplicate]了解 JavaScript 同步与异步 [重复]
【发布时间】:2017-12-06 01:42:40
【问题描述】:

我是 JavaScript 新手,尤其是 Node.js,我有 2 个函数要尝试执行。一个从文件中获取数据并将其传递给一个列表,另一个从该列表中读取以从文本文件中获取其中一行。我的代码完美无缺,除了第二个函数在第一个函数之前执行,考虑到第二个函数需要第一个函数的信息才能成功执行,这显然是一个问题。

let names = [];

function loadNames() {
  var reader = new LineReader("names.txt");
  reader.on("line", function (line) {
  names.push(line);
  console.log("length " + names.length)
  });
}

function getName() {
  console.log(names.length);
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      console.log("Loaded - " + name);
 }
  console.log("what is wrong with this thing?")
}

加载名称() 获取名称()

预期输出:

length 1
length 2
length 3
length 4
length 5
length 6
length 7
length 8
length 9
length 10
10
Loaded - 1
Loaded - 2
Loaded - 3
Loaded - 4
Loaded - 5
Loaded - 6
Loaded - 7
Loaded - 8
Loaded - 9
Loaded - 10
what is wrong with this thing?

实际输出(除了括号中的所有内容):

0 (from getName -> console.log(names.length))
what is wrong with this thing? (from getName)
length 1 (from loadNames -> console.log("length" + names.length))
length 2 (from loadNames -> console.log("length" + names.length))
length 3 (from loadNames -> console.log("length" + names.length))
length 4 (from loadNames -> console.log("length" + names.length))
length 5 (from loadNames -> console.log("length" + names.length))
length 6 (from loadNames -> console.log("length" + names.length))
length 7 (from loadNames -> console.log("length" + names.length))
length 8 (from loadNames -> console.log("length" + names.length))
length 9 (from loadNames -> console.log("length" + names.length))
length 10 (from loadNames -> console.log("length" + names.length))

【问题讨论】:

  • console.log("Loaded - " + names); name,而不是names
  • getName 和 loadNames 是怎么调用的?
  • @epascarello 参考我的最新编辑 =)
  • 所以你点了一个比萨,而你正在做的是在送达之前尝试吃掉比萨。您需要做的是在 loadNames 进行异步调用之后调用您的 getName。这就是承诺或回调发挥作用的地方。

标签: javascript node.js asynchronous synchronous line-by-line


【解决方案1】:

网上有 plenty of great resources 可以了解 JavaScript 的异步特性。

对于您的具体问题,library I think you're using 提供了解决方案。

reader.on('end', function () {
    getName()
}

【讨论】:

    猜你喜欢
    • 2017-09-20
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多