[英]Javascript Async Await Code Execution Order
I'm stumped why loopCafes runs before buildCafeList in this example. 我很困惑为什么在本示例中loopCafes在buildCafeList之前运行。 I need to build an array and pass it along for additional modification, but the execution order is reversed.
我需要构建一个数组并将其传递以进行其他修改,但是执行顺序相反。
The output returns: 输出返回:
loopCafes: 0 loopCafes:0
getCafeList 8 getCafeList 8
getCafeList 16 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();
fs.readdir
is an async function that accepts a callback. fs.readdir
是一个异步函数,它接受回调。
Consequently, buildCafeList
returns immediately (since you marked it async
and didn't include an explicit return
statement it returns a promise that resolves immediately). 因此,
buildCafeList
立即返回(由于您将其标记为async
并且不包含显式的return
语句,因此它返回立即解决的buildCafeList
)。
Later on, the callback for fs.readdir
is triggered and the value you are logging is reported. 稍后,将触发
fs.readdir
的回调并报告您正在记录的值。
You need to wrap fx.readdir
in a promise and resolve it when you get the data you want in the callback. 您需要将
fx.readdir
包装在一个promise中,并在回调中获取所需数据时fx.readdir
进行解析。 buildCafeList
needs to return that promise. buildCafeList
需要返回该承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.