首页 > 解决方案 > React.js,在所有 getDownloadURL 函数完成后打印一些东西

问题描述

我正在尝试从 Firebase 获取所有 URL。所有getDownloadURL完成后我需要打印一些东西。我试图在.then(function()){}之后添加storageRef.listAll(),但它不起作用。有人能帮我吗?太感谢了!

  getAllURL = product => {

       // Get all the images from the firebase  
        var storage = firebase.storage();
        var that = this;
        const storageRef =  storage.ref(`image/${product}`)

        storageRef.listAll().then(function(result) { 
          result.items.forEach(function(imageRef) {
                imageRef.getDownloadURL().then(function(url) {    

                  let a = 'a'            
                  that.state.temp3.push(a)
                  console.log("789")

                }).catch(function(error) {});

                console.log("123")
         })
          console.log("456")
       })            
   }

标签: javascriptreactjs

解决方案


我声明了一个名为的变量promises并将所有承诺分配给它。在那之后,我曾经Promise.all等待所有的承诺得到解决。

getAllURL = product => {
  // Get all the images from the firebase
  var storage = firebase.storage();
  var that = this;
  const storageRef = storage.ref(`image/${product}`);

  storageRef.listAll().then(function(result) {
    const promises = result.items.map(function(imageRef) {
      return imageRef
        .getDownloadURL()
        .then(function(url) {
          let a = "a";
          that.state.temp3.push(a);
          console.log("789");
        })
        .catch(function(error) {});
    });

    Promise.all(promises)
      .then((results) => console.log('Promises resolved', results))
  });
};


推荐阅读