Search code examples
javascriptfirebasefirebase-storage

Can't log path of uploaded images outside of foreach loop


I simply want to get download urls from firestorage and push it to empty array.

In handleSubmit I try this but it logs empty array.. if I try it inside it logs correctly

 let images = [];
thumbnail.forEach(async (file) => {
  const uploadPath = `property/${user.uid}/${file.name}`;
  const imgRef = ref(storage, uploadPath);
  await uploadBytes(imgRef, file);
  images.push(await getDownloadURL(imgRef));
  console.log(images); //Logs correct array of urls
});

console.log(images);// Logs empty array

Solution

  • Your callbacks are async. The console.log is firing before the callbacks have completed.

    To wait for all of the async callbacks to complete before logging use Promise.all() with map to return the promises and wait for them.

    let images = [];
    Promise.all(thumbnail.map(async (file) => {
      const uploadPath = `property/${user.uid}/${file.name}`;
      const imgRef = ref(storage, uploadPath);
      await uploadBytes(imgRef, file);
      images.push(await getDownloadURL(imgRef));
      console.log(images);
    }).then(() => {
      console.log(images);
    });
    

    You can improve on this further by returning from the callback and removing the temporary images array

    Promise.all(thumbnail.map(async (file) => {
      const uploadPath = `property/${user.uid}/${file.name}`;
      const imgRef = ref(storage, uploadPath);
      await uploadBytes(imgRef, file);
      return await getDownloadURL(imgRef);
    }).then((images) => {
      console.log(images);
    });