Search code examples
javascripttypescriptes6-promise

Promise stuck on pending Reactjs


Why is my promise still pending. I have modal that has a form submit inside of it. I am trying to return the base64 string of the CSV file. this seems to return what i want but it gets stuck on pending

    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;
    };

Solution

  • you have to await the convertBase64 function when you call it. because the console.log will run before the .then.

    and to await the convertBase64 function, you'll have to add the async keyword before defining the convertBase64 function.