Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading