What is the best way to extract the value from a resolved Promise?

Currently, I am attempting to read a file uploaded by the user and convert it into a String using two functions.

The first function is handleFileInput:

handleFileInput(event){
  setTimeOut(async()=>{
   let abcd= await this.convertFileToString(this.file) //the file has been uloaded successFully at this point
   console.log(abcd) //this prints the enitre fn given in the resolve method
  },3000)
}

The second function is convertFileToString:

convertFileToString(file){
  return new Promise((resolve, reject)=>{
      let fileReader = new FileReader();
      fileReader.readAsText(file);
      resolve(fileReader.onload = (event) =>{
        this.XMLAsString=fileReader.result as String 
      })
    })
}

When printing the value of abcd in the console, I receive the following output:

ƒ (event) {
 _this.XMLAsString = fileReader.result;
}

I am still fairly new to the concept of async/await and Promises, and I understand that a promise is the only asynchronous thing I can await. My goal is to store the value of the uploaded file, converted to a String, in the variable abcd. How can I achieve this? Do I need to return a promise, and if so, how do I access the value of the file read as a String and store it in abcd?

Answer №1

Your transformFileToString method appears to have a slight mistake: you should call the resolve() function within the onload event handler, not the other way around:

transformFileToString(file){
  return new Promise((resolve, reject)=>{
      let fileReader = new FileReader();
      fileReader.readAsText(file);
      fileReader.onload = (event) => {
          resolve(event.target.result);
      }
    })
}

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

Identify the category of the component

Using a Link component from version 4.0.0-beta.2, I am exploring its capability to override the root element with a field called component. My goal is to wrap the Link component in a new component called MyLink and pass a custom component through props: ...

Shifting Icon to the Right within the Drawer Navigator Toolbar

While modifying the example code for Material UI's drawer navigator, I decided to enhance it by adding a notification icon and a checkout icon with the Admin Panel typography in the toolbar. However, I encountered an issue where the checkout icon app ...

Creating Awesome Icons in Kendo Grid with Code In this tutorial, we will learn how to programm

Looking to have a Kendo grid display a green fas-fa-clock icon if isActive is true, and a grey far-fa-clock icon if false. Clicking on the icon should toggle between true and false. Currently, the grid just shows the word true or false in the column. Cod ...

Having difficulty with pagination within a callback function

I have been attempting to paginate in a call to a callback function, but I am encountering an error on the second call. Here is what my function does: let content = '' let size = 100 let from = 1 function result(size, from, callback) { ap ...

The content inside an HTML element and covertly deciphered quotations

SETTING THE SCENE: Hidden within the page lies a perfectly structured JSON object, wrapped in a div. Within this object are HTML values encoded with double-quotes, creating a unique challenge: "additionalInfo": "If you need more help, please visit &l ...

Using jQuery to select the third element from every group of six

I am attempting to select the 3rd .foo element out of every set of 6. To clarify, here is a brief example: 1 2 3 (this) 4 5 6 1 2 3 (this) 4 5 6 and so on... So far, I have only managed to target every 3rd element, which is not exactly what I need beca ...

Handling an Express server that receives a request with no data

I'm struggling with a problem where I am unable to retrieve a basic JSON object. When I log it to the console, all I see is {}. Let me showcase the server code below: const express = require("express"); const app = express(); app.listen(3000); app.us ...

Press `Enter` to confirm your selection in the BootstrapVue message box input box

Using Vue version v2.6.12 BootstrapVue version v2.21.2 Is there a way to confirm by pressing Enter instead of manually clicking OK? let text this.$bvModal.msgBoxConfirm(<input vModel={text} />) ...

The component does not contain the specified property

One Angular 4 component that I have is like this: export class MenuComponent { constructor(private menuService: MenuService) { } @Input(nodes):any; getMenu(path:string): void { this.menuService.getData(path).subscribe(data => { // Re ...

Tips for setting up a range slider for decimal numbers

I have implemented the following code for a range slider. It works perfectly fine for integer values like 1 and 100, but I am facing issues when trying to use decimal values. I attempted to substitute 1 with 0.1 but it did not yield the desired result. ...

What specific blur algorithm is utilized by the Flash platform within their blur filter implementation?

I'm in the process of translating AS3 code to JavaScript, and I've come across an AS3 application that utilizes Flash's built-in Blur Filter Could someone provide insight into the blurring algorithm used by this filter or suggest ways to re ...

Adding a new row to a Bootstrap table while maintaining the consistent style

Is there a way to dynamically add a new table row with different styling using jQuery? I'm facing this particular issue and need help in solving it. Below, I have included some screenshots of my code and the view for better understanding. Here is the ...

Exploring uncharted territory with the Navigator component in React Native

I am experiencing an issue with undefined navigator when using React Native MessageTabs: _onPressItem = (item) => { const { navigate } = this.props.navigation; //console.log(JSON.stringify(item)); navigate('SingleConversation', {id ...

The attempt to create the property 'and_ff' on the string 'and_chr 89' has failed

Encountering an issue with a Lambda function, I receive an error that does not occur when running the same code within an Express app. I'm puzzled. Data returned by caniuse.getLatestStableBrowsers(); [ 'and_chr 89', 'and_ff 86& ...

Combine collapse and popover in Bootstrap 3 for enhanced functionality

I'm facing some issues trying to use the badge separately from the collapse feature. $(function (e) { $('[data-toggle="popover"]').popover({html: true}) }) $('.badge').click($(function (e) { e.stopPropagation(); }) ) Check o ...

Tips for utilizing functions in an inline HTML translation pipe

My objective is to streamline the code by using the Angular translate pipe. Currently, I find myself using 8 curly brackets and repeating the word "translate" twice... there must be a more efficient approach. Here is my current code setup: <s ...

Prisma Hack: excluding properties in type generation

EDIT hiding fields in the TypeScript definitions may pose a hidden danger: inaccessible fields during development with intellisense, but accidentally sending the full object with "hidden" fields in a response could potentially expose sensitive data. While ...

Creating a sticky v-stepper-header while scrolling in VuetifyJS

Can anyone help me figure out how to make the <v-stepper-header> component stay sticky when scrolling? I attempted to create custom CSS for this but was unsuccessful. Below is a snippet of code that I tried: <v-stepper v-model="step"&g ...

JavaScript code that opens a URL in a new tab with proper formatting

I'm having trouble figuring out how to make my JavaScript open a URL in a new tab. Here is the script: function viewSource(){ var webcache = "http://webcache.googleusercontent.com/search?q=cache:"; var request = "&prmd=ivn&strip=0& ...

Having difficulty understanding Symbol.iterator and the return value type in a for-of loop while using TypeScript

Currently, I am delving into type script and embarking on a journey to learn how to craft generic containers for educational purposes. I have developed a LinkedList class with the intention of incorporating the ability to iterate over it, like so: for (co ...