0

I have an array,That contain some records with image.I'm trying to do is,convert image url in to base64 and assign new records into new Array.but i'm getting empty array.

  var newArray = [];

    devices.map(async (data) => {

     const imgData = await axios.get(data.image[0], { responseType: 'arraybuffer' })
     let returnedB64 = Buffer.from(imgData.data).toString('base64')
     newArray.push([data.identifier, data.model, data.imei,
               data.locationText, returnedB64])

    })

 console.log("Final array --->", newArray)  //i'm getting empty
Tje123
  • 729
  • 17
  • 44
  • Last `console.log` statement will execute _before_ async code executes and returns the required data. – Yousaf Aug 10 '21 at 10:01
  • @Yousaf yes thats what i want to resolve – Tje123 Aug 10 '21 at 10:04
  • 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) – Yousaf Aug 10 '21 at 10:05

1 Answers1

0

You don't await for the response, so your array is empty when console.log gets executed. the correct approach is:

Promise.all(devices.map(async (data) => {
     const imgData = await axios.get(data.image[0], { responseType: 'arraybuffer' });
     const returnedB64 = Buffer.from(imgData.data).toString('base64');
     return [data.identifier, data.model, data.imei, data.locationText, returnedB64];
})).then(allResults => {
     console.log("Final array --->", allResults);
});
Mosius
  • 1,602
  • 23
  • 32