【发布时间】:2018-12-15 13:12:44
【问题描述】:
我很困惑为什么在这个例子中 loopCafes 在 buildCafeList 之前运行。我需要构建一个数组并将其传递给其他修改,但执行顺序是相反的。
输出返回:
loopCafes:0
getCafeList 8
getCafeList 16
const fs = require("fs");
const JSON_FOLDER = "./reports/";
let cafes = [];
const buildCafeList = async () => {
fs.readdir(JSON_FOLDER, function(err, list) {
if (err) throw err;
list.forEach(function(file) {
let thisJSON = JSON_FOLDER + file;
fs.readFile(thisJSON, function(err2, data) {
if (err2) throw err2;
let thisJSON = JSON.parse(data);
for (let i = 0; i < thisJSON.businesses.length; i++) {
let thisCafe = thisJSON.businesses[i];
cafes.push({
alias: thisCafe.alias,
name: thisCafe.name,
url: thisCafe.url,
address1: thisCafe.location.address1,
city: thisCafe.location.city
});
}
console.log("getCafeList", cafes.length); // 8, 16
});
});
});
};
const loopCafes = async () => {
console.log("loopCafes:", cafes.length); // 0
for (let k = 0; k < cafes.length; k++) {
console.log(k, cafes[k].name);
}
};
const buildReport = async () => {
const getCafeList = await buildCafeList();
const showCafeList = await loopCafes();
};
buildReport();
【问题讨论】:
标签: javascript arrays node.js async-await