Ad

Promise Is Still Been Returned After Await When Converting Image To Base64 String

- 1 answer

I have the method below that converts an image to base64 string

  const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });

Then I decide to use this function like below:

    let base_strings = files.map(async file => {
      let image = await toBase64(file);
      console.dir(image); //this console base string
      return image;
    });

but when I try to access my base_string array, I still get a promise like below:

enter image description here

I am not exactly sure of what I am doing wrong, I need to be able to get my base64 string in the array.

Ad

Answer

Try using Promise.all() like this:

let base_strings = files.map(file => {
  return toBase64(file);
});

const myImages = await Promise.all(base_strings);
Ad
source: stackoverflow.com
Ad