Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

How to wait for the download url in javascript firebase storage?

I have a map which will take an array of files and will return an array of download urls from firebase storage.

const imageUrls = images.map((image, index) => {
    const imageUploadTask = storage()
      .ref(`products/${dataUser.name}/${name}/${image.name}${index}`)
      .put(image);

    imageUploadTask.on(
      "state_changed",
      (snapshot) => {},
      (error) => {
        console.log(error);
      },
      () => {
        storage()
          .ref(`products/${dataUser.name}/${name}/${image.name}${index}`)
          .getDownloadURL()
          .then((url) => {
            console.log(url);
            return url;
          })
          .catch((err) => {
            console.log(err);
          });
      }
    );
  });

When I log imageUrls array it returns an array of undefined. But in the console I see the urls logged after some time. It means urls are uploading but the code is not waiting for it and returns when the urls are not defined.

What am I doing wrong? How to make it work?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to set a separate variable in which you will .push(url) push urls to. see my example below:

    var imageUrls = []; // <======== set this as a separate variable and remove it from the next line
    
    images.map((image, index) => {
        const imageUploadTask = storage()
          .ref(`products/${dataUser.name}/${name}/${image.name}${index}`)
          .put(image);
    
        imageUploadTask.on(
          "state_changed",
          (snapshot) => {},
          (error) => {
            console.log(error);
          },
          () => {
            storage()
              .ref(`products/${dataUser.name}/${name}/${image.name}${index}`)
              .getDownloadURL()
              .then((url) => {
                console.log(url);
                imageUrls.push(url); // <============= add this line here
                return url; // <====== you can remove this
              })
              .catch((err) => {
                console.log(err);
              });
          }
        );
      });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...