我是 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))