Reactjs Promise left hanging in limbo

How can I resolve the pending status of my promise? I have a modal with a form submit in it, where I am trying to retrieve the base64 string of a CSV file. While my code seems to be returning the desired result, it remains stuck in a pending state.

    const convertBase64 = (file: any) => {
        return new Promise((resolve, reject) => {
            const fileReader = new FileReader();
            fileReader.readAsDataURL(file);
            fileReader.onload = () => {
                resolve(fileReader.result);
            };
            fileReader.onerror = (error) => {
                reject(error);
            };
        });
    };
const handleFileRead = (file: File) : string | null => {
        const base64 = convertBase64(file).then(
            ret => {
                return ret;
            },
            err => {
                console.log(err);
                return null;
            });
        console.log("handleFileRead after conversion:", base64);
        return null;
    };

Answer №1

Make sure to use the await keyword when calling the convertBase64 function to ensure it runs properly before the console.log statement. Adding the async keyword before defining the convertBase64 function will allow you to await its execution.

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

Signature of the method relies on the method call made earlier

I am currently tasked with implementing a value transformation process that involves multiple steps. To ensure reusability of these steps, a proposed architecture allows for passing steps to the transformation function. For example, transforming a long str ...

The challenges of updating AngularJS partial templates and handling refresh in 2-way binding

I've encountered an issue with a partial template that's loaded outside of my ng-view, complete with its own controller. Here's a breakdown. Basic template layout <html ng-app="myApp"> ... <div ng-include src="'myPartia ...

Postman Guide: Mastering the Evaluation of JSON Arrays

One of the features in Postman allows users to save a specific field from the response body as a variable and then utilize that variable in a subsequent call. For instance, after my initial call to the web service, the response body contains: [ { "id" ...

What improvements can I implement to enhance the clarity and functionality of this form handler?

As a beginner working on my first Next.js app, I'm facing some challenges that seem more React-related. My app allows users to add and edit stored food items and recipes, requiring me to use multiple submit form handlers. Each handler involves: Che ...

Sending properties through the React Router to a specific component

Within my component, I have a material table that triggers a function when the edit button is clicked: //MaterialTable.js ... const handleEdit = (e, Data) => { console.log(Data) return(<EditFunction id={Data.id} />) ... The purpose of ...

Ways to ensure your Javascript code only runs based on the specific browser

I need a Javascript code to run depending on the browser version. Specifically, if the browser is not IE or is IE 9+, one piece of Javascript should be executed. If the browser is IE8 or lower, another piece of Javascript should be executed. My attempt to ...

Which is the better choice for simply invoking a service method - subscribe or toPromise?

When implementing the search method below, I simply assign the value of BehaviourSubject in the service. However, I am unsure whether it is possible to execute this operation without using either subscribe() or toPromise() after the .pipe() block in the ...

Shifting and positioning the card to the center in a React application

I am currently constructing a React page to display prices. To achieve this, I have created a Card element where all the data will be placed and reused. Here is how it appears at the moment: https://i.stack.imgur.com/iOroS.png Please disregard the red b ...

Switch the checked status of an input dynamically using jQuery function

It seems like I might be overlooking something quite obvious, but I can't figure out why this jquery function is behaving inconsistently. HTML: <label id="income_this_tax_year"> <div class="left"> <p>Have you had Self-Employm ...

Removing the Shadow from Material UI's Dialog Box

I am currently struggling with the Material UI dialog component that displays information about a location marker. My issue is with disabling the unattractive box shadow that surrounds the component. Despite setting box-shadow: none and trying different so ...

Upon successfully maneuvering vendors who fail to load the NEXT.JS Link

Here is an image that is not displaying properly. The navbar's responsiveness seems to be causing the issue. return ( <Link key={index} href={'/'+item.id} > <li className="nav-item dropdown position-stati ...

Utilizing a Meteor Method within a Promise Handler [Halting without Throwing an Error]

I've been working on integrating the Gumroad-API NPM package into my Meteor app, but I've run into some server-side issues. Specifically, when attempting to make a Meteor method call or insert data into a collection within a Promise callback. Be ...

jQuery - Enhancing User Experience with Dynamic Screen Updates

Is there a way to update the screen height when resizing or zooming the screen? Whenever I zoom the screen, the arrows break. I'm also curious if the method I'm using to display images on the screen is effective. It's supposed to be a paral ...

The React axios request triggers the UseEffect cleanup function to terminate all subscriptions and asynchronous tasks

I'm currently retrieving data from my API using axios, but the requests are not inside a useEffect function. In fact, I haven't used useEffect at all. Here's a snippet of my code: JSX: <form onSubmit={onSubmitLogin}> <div c ...

I am having issues with sendKeys and click() functions in my code. I am unable to access the elements using Protractor's javascript

<input class="form-control validation-field ng-dirty ng-touched ng-invalid" placeholder="Password" type="password"> Despite using the element to retrieve it, I am unable to send keys and no error message is displayed. This issue persists in both Fir ...

Prevent the risk of revealing your LinkedIn API key within HTML code

For my website, I am looking to incorporate the Sign In With LinkedIn feature for user logins. The initial example snippet provided in the LinkedIn API docs is as follows: <script type="text/javascript" src="//platform.linkedin.com/in.js"> api_k ...

Transferring Visitor's Country Code Between Two Web Applications Using .NET Framework (ASP/MVC)

I'm currently working on developing an application that collects user information such as country, city, and IP address of the website they're visiting. This data is then sent to another web application of mine, which will be automatically update ...

Building a Wordpress website with AJAX functionality using only raw Javascript and no reliance on Jquery

So, I have a custom script named related-posts.php, and I want to insert it into posts only when the user scrolls. In addition, I have an enqueued script file in WordPress that loads in the footer, where I have written AJAX code like this: var xmlhttp = ...

The error message "item is not defined in nodejs" indicates that the variable

I am facing an issue while trying to retrieve data from a JSON file using Node.js and Express. I have defined the methods with exports, but I keep getting errors in my browser. I am unsure why it is not functioning correctly, as I have specified the metho ...

Dependencies for Grunt tasks

I am facing some issues with a grunt task named taskA that was installed via npm. The task has a dependency on grunt-contrib-stylus, which is specified in the package.json file of taskA and installed successfully. However, when I run grunt default from the ...