2017-02-13 66 views
0
for (var i = 0; i < e.target.files.length; i++) { 
    var storageRef = firebase.storage().ref('user_files/' + e.target.files[i].name).put(e.target.files[i]); 
    storageRef.on('state_changed', null, null, function (snapshot) { 
     var downloadURL = storageRef.snapshot.downloadURL; 

     //i need all the files URL 
     //but always get the last file URL 
    }); 
} 

回答

0

當您撥打put()即返回UploadTask。除了您使用的on()方法外,它還實現了then()。這意味着你可以使用它作爲一個承諾,因此使用Promise.all

for (var i = 0; i < e.target.files.length; i++) { 
    var promises = firebase.storage().ref('user_files/' + e.target.files[i].name).put(e.target.files[i]); 
    Promise.all(promises).then(function(results) { 
     var downloadURLs = results.map(function(taskSnapshot) { 
      return taskSnapshot.downloadURL 
     }); 
    }) 
} 

一個上面的代碼稍微現代版:

var files = firebase.storage().ref('user_files'); 

var promises = e.target.files.map((f) => files.child(f.name).put(f)); 

Promise.all(promises).then((results) => { 
    var downloadURLs = results.map((taskSnapshot) => taskSnapshot.downloadURL); 
})