I am trying to write a function that given a list of ids goes to firebase storage and retrieves the download URL for each id and saves the URLs in an array in the same order as the ids array. On testing I have found that the download URLs are returned in a random order. Below is some scaled down code of the aforementioned function.
1) Is there a way to cause the returned URLs to arrive in the correct order?
2) The setTimeout function is used after the loop to wait for 3 seconds otherwise the urlsToDownload array is empty. Is there a more accurate way to wait until all the URLs have been downloaded?
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);
}