Firebase storage upload multiple files and got their download URLs at once

I want to upload multiple files by using Firebase Firestore and get their download URLs at once, this is how I have done.

 const promises = [];

    imgFileList.forEach((file, index) => {
      const uploadTask = storage.ref(`instagram/${file.name}`).put(file);
      promises.push(uploadTask);
      uploadTask.on(
        'state_changed',
        (snapshot) => {},
        (err) => alert(err.code),
        async () => {
          const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
          console.log(downloadURL, index);
        }
      );
    });

    Promise.all(promises)
      .then(() => {
        console.log(uploadedMediaList, 'all');
      })
      .catch((err) => alert(err.code));

and this is what I got

result

as you can see, in the code above, I Promises.all() array of promises and it is not return download URL in order as I expected, please show me how to deal with it, I want to get list of download URLs at in the then block of Promise.all(). Thank you so much and I am sorry for my bad English. Have a good day

Upvotes: 2

Views: 1075

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

When you call put on a storage reference, it returns a promise. So you don't need to use the on listener, but can instead just wait for that promise to resolve before calling getDownloadURL().

const promises = imgFileList.map((file, index) => {
  let ref = storage.ref(`instagram/${file.name}`);
  return ref.put(file).then(() => ref.getDownloadURL());
})
Promise.all(promises)
  .then((uploadedMediaList) => {
    console.log(uploadedMediaList, 'all');
  })
  .catch((err) => alert(err.code));

Upvotes: 1

Related Questions