Search code examples
reactjstypescriptpromisebase64

How to convert a Promise array (original File array) into an array of string values?


In short, I have a function that converts File type values into base64 string type values (as advised by How to convert file to base64 in JavaScript?):

export const customConvertFileToBase64String = (file: File) =>
  new Promise<string | ArrayBuffer | null>((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
  });

However, as I use the fucntion with an array of File type values, it returns Promise<string | ArrayBuffer | null>[]:

const getFullValue = (files: File[]) => files.map(async (file) => 
  await customConvertFileToBase64String(file));

And I tried the below method to convert it to (string | ArrayBuffer | null)[], with this question - How to extract data out of a Promise (not too familiar with the Promise type):

// REMARK: not working for both map() and forEach() function
const getFullValue = (files: File[]) => files.map(async (file) => 
  await customConvertFileToBase64String(file)).map(async (promise) => 
    await promise.then((result) => result));

Solution

  • The problem is that when you use map in an array and the callback is async, what you get as a result is an array of Promise. So getFullValue returns Promise<string | ArrayBuffer | null>[]:

    const getFullValue = (files: File[]) => files.map(async (file) => 
      await customConvertFileToBase64String(file));
    

    You can use Promise.all to wait for all the promises to be completed. You will get (string | ArrayBuffer | null)[] (no promises) as result:

    const getFullValue = (files: File[]) => Promise.all(
        files.map(customConvertFileToBase64String)
    );
    
    getFullValue.then(result => {
      // result is (string | ArrayBuffer | null)[]
    })