Store the filereader output in a variable for future reference

I am struggling to find a simple answer, even though my code is simple. I attempted the following approach, but every time I try to console.log my testResult, it always returns null. How can I correctly save data from a file?

public getFile(
    sourceFile: File
  ): string {
    let testResult;
    const file = sourceFile[0]
    const fileReader = new FileReader();
    fileReader.readAsText(file, "UTF-8")
    fileReader.onloadend = (e) => { 
      testResult = fileReader.result.toString()
    } 
    console.log(testResult)
    return testResult
  }

This issue ties back to previous topics where I struggled to handle loading a JSON file, translating it, and displaying it to the user. If I could save this file outside of onloadend, I believe I could overcome the remaining challenges (previous methods failed, and this one sets me back at the start).

Answer №1

The issue you're facing is a common one that relates to asynchronous operations. The function assigned to the onloadend request is only called when the loadend event is triggered. However, the rest of the code does not wait for this event and continues executing. This means that the console.log will be executed immediately, returning an empty testResult.

To address this, place the console.log(testResult) line within your onloadend handler:

fileReader.onloadend = (e) => { 
  testResult = fileReader.result.toString();
  console.log(testResult);
}

At this point, testResult will no longer be empty and you can proceed with handling it inside this function. However, if you want the getFile method to be reusable and return the testResult for processing elsewhere, you should wrap it in a Promise like so:

public getFile(
    sourceFile: File
  ): Promise<string> {
    return new Promise((resolve) => {
      const file = sourceFile[0]
      const fileReader = new FileReader();
      fileReader.onloadend = (e) => { 
        const testResult = fileReader.result.toString();
        resolve(testResult);
      }
      fileReader.readAsText(file, "UTF-8");
    });
  }

Now, whenever you need to access a file, you can use the yourInstance.getFile method as shown below:

yourInstance.getFile().then(testResult => {
  // Do whatever you need here
  console.log(testResult);
});

Alternatively, you can use async/await to process the result:

async function processResult() {
  const testResult = await yourInstance.getFile();
  // Do whatever you need
  console.log(testResult);
}

If you're unfamiliar with promises and/or async/await, you can learn more about them here and here.

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

How can you assign a value to a JSON key using the @value tag?

The JSON string format that I received is from an API and it contains various dropdown options with their corresponding values. Each parameter ID has a separate @value, which can be dynamically set to 0, 1, 2, 3, or 4. For example, when @para-id = 2572: ...

Tips for showing nested JSON data in a PrimeNG table within Angular version 7

I am struggling to display nested json data in a PrimeNG table. When I retrieve the data using an HTTP service, it appears as [object][object] when displayed directly in the table. What I want is to show the nested json data with keys and values separated ...

Transform your flat JSON data into a tree structure using AngularJS

Looking for assistance with creating a hierarchical Kendo grid using JSON data as the data source. I have searched for solutions that compare data based on parent-id values and arrange them accordingly, but since I do not have such a column in my current J ...

Troubleshooting issues with JSON compatibility within the OnChange event

Initially, I wrote this code to retrieve a single data point. However, I realized that I needed more fields returned when the drop-down select menu triggered an onchange event. So, I switched to using JSON, but now it's not returning any data. The dro ...

Utilizing Emotion CSS to incorporate images into buttons

I'm trying to add some style to two buttons, Up and Down, by using emotion CSS but I'm having trouble. Currently, I typically style my elements within a function. Is there a way for me to accomplish this with emotion CSS? I checked out but still ...

Showcasing Array information in Json format

I am currently working on displaying the JSON output of a dynamically generated flowchart. I have gathered all the details of the dropped elements in an array named finalArray, and then integrated this data into the JSON representation. All details are bei ...

Error encountered when pushing Angular data to Django for user login form: 'Unexpected token < in JSON at position 2' while attempting to parse the JSON

I believe the < symbol is appearing because the response is in HTML or XML format. This is the section of my code where the login process is failing. public login(user) { this.http.post('/api-token-auth/', JSON.stringify(user), this.ht ...

When invoking a JavaScript method, the context variable 'this' is lost

I have developed a basic pointer to a method like this: export class SmbwaService { getExistingArsByLab(labId: number): Observable<SmwbaAr[]> { this.otherMethod(); } otherMethod(): void { } } let method: (x: number) => ...

Exploring connections among Array Objects on a Map

Here are some JSON examples of Pokemon Battles: [ { "battleID": "1", "trainers": [ { "LastName": "Ketchum", "ForeName": "Ash" }, { "LastName": "Mason", ...

What is the best way to clear an array?

Yesterday I had a query regarding JSON Check out this link for details: How to return an array from jQuery ajax success function and use it in a loop? One of the suggested answers included this script: setInterval(updateTimestamps,30000); var ids = new ...

How can models be aggregated in SQL by connecting them through other models?

I am working with a backend express API that utilizes sequelize. In my sequelize models, a Citizen is linked to a Street, which in turn is associated with a Town, and the Town is connected to a State. I can easily count the citizens on a specific Street by ...

"Encountering an issue with opening a form in a child component from the parent - receiving an error message 'unable to access

Here's the scenario: I am working with a list of companies that each have an array of projects as one of their variables. The desired functionality is to display the list of companies in the parent component/html, and only open a child component to sh ...

Transitioning from Javascript to Typescript with the integration of Knockout and DevExtreme interfaces

Currently facing challenges with transitioning from Javascript to Typescript, especially when it comes to creating a devextreme control. In the past, I would set up an object in my viewmodel for devextreme controls like this: self.myButton = { text: &a ...

Achieve Grid Paging with JSON in Ext GWT by configuring the total number of records for pagination

Currently, I am utilizing Ext GWT to work on a project that involves a grid with paging and JSON. I am struggling to figure out where to set the total number of records in the paging configuration. The paging grid is not functioning correctly because it ...

Fetching a JSON file with a 404 error using $http.get and handling it with

I recently came across a set of Angular videos on YouTube where I learned that .success is no longer supported, and we should use .then instead. However, when trying to access both a .json file and a .txt file, I kept encountering a 404 error. Some have po ...

Combining two observables into one and returning it may cause Angular guards to malfunction

There are two important services in my Angular 11 project. One is the admin service, which checks if a user is an admin, and the other is a service responsible for fetching CVs to determine if a user has already created one. The main goal is to restrict ac ...

Testing the window object using Jest

I have created a function that simulates a hostname. This function is defined before the actual test, prior to the describe block. const mockHost = (hostname: string) => { global.window = Object.create(window); Object.defineProperty(window, ' ...

Ways to retrieve a list of items along with their respective quantities

I am looking to retrieve a list of objects instead of just the count(ID) I want my code to return an array that includes the list of objects for each date Here is my current code: $data['myresponse'] = DB::table("products") ...

What is the meaning behind the phrase "JSON specification solely permits a single top-level entity"?

In my coding editor, specifically IntelliJ, I came across a test.json file that has an interesting problem. The second json record is triggering an error message stating "Json standard only allows one top-level value". However, upon closer inspection, th ...

What could be the reason behind jQuery.ajax not being able to return JSON data within a loop

I am currently attempting to iterate through an array in JavaScript with array values appended to the end of a variable named "url" in order to retrieve the corresponding JSON data from a website. However, it seems to be returning an error message: {"Error ...