Home > Mobile >  Convert array of images to base64 using readAsStringAsync in React Native
Convert array of images to base64 using readAsStringAsync in React Native

Time:10-20

I have the following code:

export const blSaveRecord = async (data) => {

  const params = new URLSearchParams()

  params.append('DocumentNumber', data.DocNumber)

  data.People.map((item, index) => {
     params.append(`Person[${index}].PersonDoc`, item.PersonDoc)
     params.append(
        `Person[${index}].Document[0].Base64File`,
        `data:image/jpg;base64,${FileSystem.readAsStringAsync(item.image, {
          encoding: FileSystem.EncodingType.Base64,
        })}`
     )
    })

    //THIS IS THE ISSUE:
    console.log(params)

    return axios
      .post(url_SaveRecord, params)
      .then(function (response) {
        return {
          status: true,
          message: '',
        }
      })
      .catch(function (error) {
        return {
          status: false,
          message: error.message,
        }
      })
  })

The issue is that the method readAsStringAsync is Async, but I cant get to work with await. I tried to call another async function to make this method and wait for it but its not possible.

The question is... how can I wait to an async function to complete inside a map? I dont want to go to next iteration until the async is complete.

Thanks.

CodePudding user response:

Promise.all async function within map callback is easier to implement:

let response=await Promise.all(data.People.map((item, index)=>{

//Your code

}))

  • Related