2017-09-10 82 views
0

我有這樣的文件名列表對象的列表:同步檢索Firebase存儲網址?

Object 1 
    Files 
    file1:1234 
    file2:2345 
Object 2 
    Files 
    file1:456 
    file2:656 

我遍歷每個對象,其中的每一個對象,我遍歷每個文件和查詢火力存儲獲取每個文件的網址。以便將其作爲超鏈接顯示給數據表。

var tableData = []; 
//Code to Loop over the objects 
    var myApp ={ fileurls:[]}; 
    var i =0; 
    angular.forEach(filesContainer.filenames, function(value, key) { 
      storageRef.child('/myfiles/'+ value) 
      .getDownloadURL().then(function(url) { 
       myApp.fileurls[i] = url; 
       i++; 
       } 
      }).catch(function(error) { 
       console.log("Error"); 
       }); 
    }); 
tableData.push(); 
//Loop over object ends here 
//invoke successcallbackfunction to display the tableData 
successcallbackfunction(tableData); 

與我上面的代碼的問題是,由於asycnhronous火力電話,myApp陣列始終是空的。我如何才能確保tableData.push()行僅在循環完成對象的文件時才能執行?

+0

一件事,你需要通過改變VAR對myApp = {fileurls []}更新JavaScript代碼; var myApp = {fileurls:[]}; ? –

+0

是粘貼錯誤代碼 – user2713255

回答

0

嘗試修改此:

angular.forEach(filesContainer.filenames, function(value, key) { 
      storageRef.child('/myfiles/'+ value) 
      .getDownloadURL().then(function(url) { 
       myApp.fileurls[i] = url; 
       i++; 
       } 
      }).catch(function(error) { 
       console.log("Error"); 
       }); 

到:

angular.forEach(filesContainer.filenames, function(value, key) { 
      storageRef.child('/myfiles/'+ value) 
      .getDownloadURL().then(function(url) { 
       myApp.fileurls[i] = url; 
       i++; 
        if (i == filesContainer.filenames.length) { 
         tableData.push(); 
         //Loop over object ends here 
         //invoke successcallbackfunction to display the tableData 
         successcallbackfunction(tableData); 
        } 

       } 
      }).catch(function(error) { 
       console.log("Error"); 
       }); 

所以一旦最後一次迭代完成後,再執行所需的代碼。

+0

時的錯字,我需要在對象循環結束而不是文件循環後進行成功回調。我的對象循環本質上是forEach on firebase查詢快照 – user2713255

+0

您的對象循環代碼在哪裏? –

0

The Reference.getDownloadUrl() function returns a Promise。因此,這意味着你可以做平時的承諾與Promise.all()收集:

var tableData = []; 
var i =0; 
var promises = []; 

angular.forEach(filesContainer.filenames, function(value, key) { 
    promises.push(
     storageRef.child('/myfiles/'+ value).getDownloadURL() 
    }); 
}); 
Promise.all(promises).then(functions(urls) { 
    var myApp ={ fileurls: urls }; 
    tableData.push(); 
    successcallbackfunction(tableData); 
}).catch(function(error) { 
    console.log("Error"); 
});