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

Is there a way to loop through objects in Angular 2

I am working with an Array of Objects named comments, and my goal is to select only the ones that have a specific post id and copy them to another array of objects. The issue I am facing is finding a way to duplicate the object once it has been identified. ...

Exploring the Concept of Extending Generic Constraints in TypeScript

I want to create a versatile function that can handle sub-types of a base class and return a promise that resolves to an instance of the specified class. The code snippet below demonstrates my objective: class foo {} class bar extends foo {} const someBar ...

Nullable Object in Vue 3 Composition API

I am utilizing the Vue 3 Composition api along with Typescript to create pinch zoom functionality using the HammerJS package. In my Vue application, I am attempting to replicate a functional example implemented in JavaScript from CodePen: https://codepen. ...

Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array: [ { id: '1', task: 'Grocery shopping', isImportant: true }, { id: '2', task: 'Meeting', isImportant: false }, { id: '3', task: &apos ...

Issue with ngRX infinite loop caused by the updateOne function in the adapter

Hey there, I'm struggling to figure out why my code is stuck in an infinite loop. I've searched online extensively but haven't found a solution that fits my specific issue. This is the code snippet causing the problem: /** * CODE ...

Encountering an error when trying to access this.$store.state in a basic Vuex

Encountered an error with return this.$store.state.counter: The property '$store' does not exist on the type 'CreateComponentPublicInstance<{}, {}, {}, { counter(): any; }, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, ...

Is your Angular app missing i18next translations?

Can Angular's i18next provider be configured to hide any value when the key is not defined? The issue arises when there is no translation defined for a specific key like my:key. I want to display an empty string in the template instead of showing the ...

The name property of event.currentTarget is now being returned as currentTarget

I am facing an issue with my handleChange function in typescript. When I try to retrieve the name attribute from a text field and log it, it returns 'currentTarget' instead of the assigned name. Additionally, the value is showing up as undefined. ...

How is it possible to utilize type assertions with literals like `false`?

When working in TypeScript, I came across an interesting observation when compiling the following code: const x = true as false; Surprisingly, this direct assertion is valid, creating a constant x with the value true and type false. This differs from the ...

Universal - Permissible data types for function and constructor arguments

In many statically typed languages, it is common to specify a single type for a function or constructor parameter. For example: function greet(name: string) { ... } greet("Alice") // works greet(42) // error TypeScript is an extension of JavaScri ...

Uploading raw data to Firebase bucket

I am currently developing a nodejs/typescript application that leverages Firebase Functions, and I am facing a challenge with uploading a JSON object to a bucket. The issue arises from the fact that the JSON data is stored in memory and not as an actual fi ...

Attempting to create a TypeScript + React component that can accept multiple types of props, but running into the issue where only the common prop is accessible

I am looking to create a component named Foo that can accept two different sets of props: Foo({a: 'a'}) Foo({a: 'a', b: 'b', c:'c'}) The prop {a: 'a'} is mandatory. These scenarios should be considered i ...

The webpack development server refreshes the page just one time

I've been searching through various issues on Stack Overflow but haven't had any luck. It seems like most solutions are for an older version of webpack-dev-server. Despite trying numerous things, my app just won't reload or rebuild more tha ...

Tips on dynamically passing values according to media queries

Within my product section, there is a total of approximately 300 products. To implement pagination, I have utilized the ngx-pagination plugin. The products need to be displayed based on media query specifications. For example, if the viewport size falls wi ...

Angular page not reflecting show/hide changes from checkbox

When the user clicks on the checkbox, I need to hide certain contents. Below is the code snippet: <input id="IsBlock" class="e-field e-input" type="checkbox" name="IsBlock" style="width: 100%" #check> To hide content based on the checkbo ...

Icon for TypeScript absent from npm package listings

Recently, I created a package and uploaded it to the npm repository. The package was displayed with an icon labeled "ts" on the website. https://i.stack.imgur.com/LoY1x.png The accompanying package.json showcased the inclusion of the "ts" icon - https:// ...

Issues with applying different styles in a React Component based on prop values are hindering the desired outcome

I am currently working on a Display component that is supposed to show an item. The item should be styled with the css property text-decoration-line, applying line-through when the Available prop is set to false, and no decoration when set to true. Howev ...

Simulate a new Date object in Deno for testing purposes

Has anyone successfully implemented something similar to jest.spyOn(global, 'Date').mockImplementation(() => now); in Deno? I've searched through the Deno documentation for mock functionality available at this link, as well as explored t ...

Using Next.js, it is not possible to use absolute imports within SASS

Having trouble utilizing @/ imports within my scss files. The variables I need are stored in src/styles/_variables.scss Here is my tsconfig.json: { "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "baseUrl": ".", "allowJs": tr ...

Utilize multiple validators.patterns within a single value for enhanced data validation

I need to implement two different patterns for the formControlName='value' based on the type selected. If type is 'A', I want to use the valuePattern, and if type is 'B', I want to use the uname pattern. This is my HTML code: ...