0

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;
    };
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Amr Mashrah
  • 177
  • 13
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) and [How to access the value of a promise?](https://stackoverflow.com/q/29516390) – VLAZ Mar 03 '22 at 16:16
  • You're not `await`ing the `Promise` returned by `Promise.then` before logging it. You're also returning `null` no matter what, you probably want to change that. – Samathingamajig Mar 03 '22 at 16:21

1 Answers1

1

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.