Await does not work on lists of promises

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.

Last Updated: 2024-11-21

If you pass an async function to map, you can't use await. You need Promise.all

I had this code:

await currentCar.images.map(async (image, index) => {
  const originalPhotoBase64 = await FileSystem.readAsStringAsync(
    image.uri,
    {
      encoding: FileSystem.EncodingType.Base64,
    }
  );
  return {
    stepNumber: index,
    originalPhotoBase64,
  };
}),

Weirdly, it output data like this in the console

  {
      "_U": 0,
      "_V": 0,
      "_W": null,
      "_X": null,
    },

The fix

await Promise.all(
  currentCar.images
    .map(async (image, index) => {
      const originalPhotoBase64 = await FileSystem.readAsStringAsync(
        image.uri,
        {
          encoding: FileSystem.EncodingType.Base64,
        }
      );
      return {
        stepNumber: index,
        originalPhotoBase64,
      };
    })
),