如何解决for循环中的状态变化?

时间:2017-02-13 07:19:16

标签: javascript firebase state firebase-storage

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
    });
}

1 个答案:

答案 0 :(得分: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);
})