The initial function is executed only after the second function has completed, as it relies on the

For a small project of mine, I've been attempting to load JSON data. However, the issue arises when the loadDefs function is executed before checking if file_data has been modified.

loadDefs(file_path:any)
    {
        let file_data:string = '';
        fs.readFile(file_path, 'utf8', (err, data:string) => {
            if (err) {
              console.error(err);
              return;
            }
            file_data = data;
            console.log(file_data);
        });
        if (file_data == '')
        {
            console.log("Data not loaded.");
            return;
        }

        const loading_defs:Array<any> = JSON.parse(file_data);
        console.log(loading_defs);
        for (let index = 0; index < loading_defs.length; index++) {
            const def = loading_defs[index];
            if (def["type"] == "DefTypeDef")
            {
                this.defs[def["uuid"]] = {};
            }
            this.defs[def["type"]][def["uuid"]] = def;
        }
    }

The section where the function is called:

    let g = new Game();
    g.loadDefs("./Defs/defTypes.json")

Here is the output, including the contents of my "./Defs/defTypes.json" file:

Data not loaded.
[
    {
        "type": "DefTypeDef",
        "uuid": "WorldObjectDef"
    },
    {
        "type": "DefTypeDef",
        "uuid": "NAME"
    }
]

I had anticipated that the code would display the json file's content and load it in accordance with the defined logic.

During troubleshooting, I attempted to read the file externally and pass it into the function later on, but encountered the same problem. Different JSON files were also tried, each with unique content, yet none were successful. I am unsure how to ensure that my code executes as intended.

Answer №1

To better understand how the fs.readFile() function works, you can refer to the documentation here. This function is asynchronous, meaning that the file content will only be accessible within the callback function provided as the third argument. To adjust your code accordingly:

loadDefs(file_path:any)
{
    let file_data:string = '';
    fs.readFile(file_path, 'utf8', (err, data:string) => {
        if (err) {
          console.error(err);
          return;
        }
        file_data = data;
        console.log(file_data);

        if (file_data == '')
        {
            console.log("Data not loaded.");
            return;
        }

        // Perform additional actions with the file content here
    });
}

If you're new to asynchronous programming, I recommend delving into this concept as it's essential for web development. A helpful starting point is the guide available here, but there are numerous resources to explore.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigation arrows for sliding`

Is there a way to add custom right/left arrows to the Ionic slider component? Demo: Check it out on Stackblitz Note: Make sure to refer to the home.html page for more details. .html <ion-slides [pager]="true" [slidesPerView]="2"> <ion ...

The functionality to verify the presence of a child element is not functioning correctly when using

Trying to determine the existence of a child, I have created a new Firebase list observable and also attempted with an object observable. Upon creating the observable, I verify if it exists or not; however, it always returns false. Database Structure: {R ...

Enhance your Next.js routing by appending to a slug/url using the <Link> component

In my Next.js project, I have organized my files in a folder-based structure like this: /dashboard/[appid]/users/[userid]/user_info.tsx When using href={"user_info"} with the built-in Next.js component on a user page, I expect the URL to dynamic ...

The promise is unexpectedly fulfilled ahead of schedule without returning the expected value from an AXIOS call

My current challenge involves making a request to a service that rapidly generates multiple strings. The problem lies in returning a promise from this service, as I lack control over the string-generation process. It is crucial for me to return a promise ...

Removing empty options from a select dropdown in Angular 9

In the process of working with Angular 9, I am currently in the process of constructing a dropdown menu that contains various options. However, I have encountered an issue where there is a blank option displayed when the page initially loads. How can I eli ...

A mistake has occurred: Unhandled promise rejection TypeError: Unable to assign the property 'devices' to an undefined object in Ionic 4 with Angular

Within my MyDevicesPage class, I am attempting to manipulate the res object and then pass it to the updateDevicesToServer method of DataService for further actions. The code compiles without errors, but at runtime, an error is thrown: ERROR Error: Uncaught ...

Maximizing the potential of NestJS apps with Docker

I am working on a NestJS project that consists of multiple apps structured as follows: my-project: -- apps; --- app-one ---- src ---- tsconfig.app.json --- app-two ---- src ---- tsconfig.app.json -- libs -- package.json -- etc... Within this project, I ha ...

What is the best way to store values in a map for future reference within a Kotlin class?

Looking to implement a map of key value pairs in Kotlin inside a class that is mutable and can be updated and referenced as needed. Research suggests that using a MutableMap would be the appropriate choice, given its ability to be updated at any point. I ...

Troubleshooting: The issue of importing Angular 2 service in @NgModule

In my Angular 2 application, I have created an ExchangeService class that is decorated with @Injectable. This service is included in the main module of my application: @NgModule({ imports: [ BrowserModule, HttpModule, FormsModu ...

The type '{ children: Element; }' is lacking the specified properties within type - NextJS version 13.0.6 with TypeScript version 4.9.3

Currently, I am delving into NextJS / TypeScript and have come across a type error. The component structure is as follows: interface LayoutProps { children: React.ReactNode; title: string; keywords: string; description: string; } const Lay ...

Exciting Update: Previously, webpack version 5 did not automatically include polyfills for node.js core modules (such as React JS, TypeScript, and JWT)!

Having trouble verifying the jwt token in React with TypeScript and encountering this error, how can I fix it? ` const [decodedToken, setDecodedToken] = useState<null | JwtPayload | string>(null); const verifyToken = (token: string) => { t ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

Error: The argument provided is of type 'unknown', which cannot be assigned to a parameter of type 'string'. This issue arose when attempting to utilize JSON.parse in a TypeScript implementation

I'm currently converting this code from Node.js to TypeScript and encountering the following issue const Path:string = "../PathtoJson.json"; export class ClassName { name:string; constructor(name:string) { this.name = name; } ...

Learn the best way to retrieve the highest number from a Array<String> in TypeScript or JavaScript

Can someone help me create a function in JS or TS that meets the following requirements? I am looking for a functional programming approach. ・Input type: Array(String) ・Output type: string or undefined Examples Input Result ["" ...

Creating a dynamic dropdown menu triggered by a button click using Angular

I am a beginner in Angular (typescript) and I am facing some challenges in adding a new dropdown menu when a user clicks a button. My main struggle is creating additional attribute fields. I'm considering keeping track of the newly added dropdowns wit ...

What could be the reason for `process.env.myvariable` not functioning in a Next.js project with TypeScript

After creating a file called .env.local in the root directory of my project, I added a variable called WEBSOCKET_VARIABLE=THIS_IS_TEXT to it. However, when I try to access it using process.env.WEBSOCKET_VARIABLE, nothing is found. What could be causing ...

How can I access a TypeScript variable from a global var set in a .cshtml file?

I have defined several variables in my .cshtml file to be used in my angular services: <script> var _APIURL = '@(Url.Content("~/Admin/api/"))'; var _AREAURL = '@(Url.Content("~/Admin/"))'; var _APPURL = &a ...

MXGraph has an issue where edges fail to be redrawn after being moved

Perhaps this question may seem trivial, but I am facing an issue in my code and seeking guidance from the community. I am working on a javascript mxGraph application within Angular7. Specifically, I have modified the ports.html example for my project. Wh ...

What is the process for initiating an Angular 2 Materialize component?

I'm new to using angular2 materialize and I've found that the CSS components work perfectly fine. However, I'm facing an issue when it comes to initializing components like 'select'. I'm unsure of how or where to do this initi ...

Is there a way to utilize ng-if within a button to reveal the remaining portion of a form using TypeScript?

Can anyone help me figure out how to make the rest of my form appear when I click on a button? I think I need to use Ng-if or something similar. Here is the code for the button: <button type = "button" class="btn btn-outline-primary" > Données du ...