Javascript异步等待代码执行顺序

时间:2018-07-06 23:18:16

标签: javascript arrays node.js async-await

在这个示例中,我很奇怪为什么 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();

1 个答案:

答案 0 :(得分:2)

fs.readdir是一个异步函数,接受回调。

因此,buildCafeList立即返回(由于您将其标记为async,并且未包含明确的return语句,因此它返回了立即解决的承诺)。

稍后,将触发fs.readdir的回调并报告您正在记录的值。


您需要将fx.readdir包装在promise中,并在回调中获取所需数据时解决它。 buildCafeList需要兑现承诺。

相关问题