1

I'm stumped why loopCafes runs before buildCafeList in this example. I need to build an array and pass it along for additional modification, but the execution order is reversed.

The output returns:

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 Answer 1

2

fs.readdir is an async function that accepts a callback.

Consequently, buildCafeList returns immediately (since you marked it async and didn't include an explicit return statement it returns a promise that resolves immediately).

Later on, the callback for fs.readdir is triggered and the value you are logging is reported.


You need to wrap fx.readdir in a promise and resolve it when you get the data you want in the callback. buildCafeList needs to return that promise.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.