0

Im working on some code to read and parse my JSON and for some unknown reason the parsed data is unable to be accessed outside of the function. My first console log will return my JSON data but the last one will not.

Is there any way to make the JSON data accessible from anywhere in the script?

JavaScript:

const fs = require("fs/promises");

...

let continueCourses;
const getCurrentCourses = async () => {
    try {
        await fs.access("./data/user-courses.json");
    } catch {
        continueCourses = { courses: [] };
    }

    if (!continueCourses) {
        continueCourses = JSON.parse(await fs.readFile("./data/user-courses.json", "utf8"));
        console.log(continueCourses);
    }
};

getCurrentCourses()
console.log(continueCourses)

JSON:

{
    "courses": [
        {
            "id": "0",
            "title": "Getting Started with Hirigana",
            "desc": "Intro"
        },
        {
            "id": "1",
            "title": "Getting Started with Katakana",
            "desc": "Intro"
        }
    ]
}

1 Answers1

0

You are calling an asynchronous function so you need to tell java script to wait for result. One of many syntaxes would be


let continueCourses;
const getCurrentCourses = async () => {
    try {
        await fs.access("./data/user-courses.json");
    } catch {
        continueCourses = { courses: [] };
    }

    if (!continueCourses) {
        continueCourses = JSON.parse(await fs.readFile("./data/user-courses.json", "utf8"));
        console.log(continueCourses);
    }
    // Return after finishing
    return continueCourses;
};

getCurrentCourses().then((result)=>{
  console.log(result);
}).catch(err=>{
  console.error('error found while running', error)
});

Zanko
  • 4,298
  • 4
  • 31
  • 54