我正在尝试编写一个函数,给出一个id列表进入firebase存储并检索每个id的下载URL,并以与ids数组相同的顺序将URL保存在数组中。在测试中,我发现下载URL是以随机顺序返回的。下面是上述功能的一些缩小代码。
1)有没有办法使返回的URL以正确的顺序到达?
2)循环后使用setTimeout函数等待3秒,否则urlsToDownload数组为空。是否有更准确的方式等待所有URL下载?
function downloadAll() {
var storageRef = firebase.storage().ref("/stuffToDownload");
var urlsToDownload = [];
var downloadIds = ['1', '2'];
for (var x = 0; x < downloadIds.length; x++) {
var downloadId = dowloadIds[x];
(function(did) {
var storageFileRef = storageRef.child(did);
storageFileRef.getDownloadURL().then(function(url) {
urlsToDownload.push(url);
}).catch(function(error) {
console.log("error");
});
})(downloadId);
}
}
}
setTimeout(function() {
console.log("finished getting file urls", urlsToDownload.length);
var index = 0;
for(index = 0; index < urlsToDownload.length; index++){
console.log(index + " " + urlsToDownload[index]);
}
}, 3000);
}
答案 0 :(得分:0)
你可以做的是等待URL下载,然后用downloadIds的长度检查urlsToDownload的长度,如果匹配调用下面的函数,
storageFileRef.getDownloadURL().then(function(url) {
urlsToDownload.push(url);
if(urlsToDownload.length==downloadIds.length){ //if you have all the files matching with downloadIds then you will get all the download URL
_callConsoleLog()
}
})
var _callConsoleLog=function(){
var index = 0;
for(index = 0; index < urlsToDownload.length; index++){
console.log(index + " " + urlsToDownload[index]);
}
}