我正在使用Firestore和Storage在Vue中做一个轻巧的仪表板。我不是专业人士,所以我陷入了应该容易的事情。我有一个函数应该根据文件名获取所有URL(这就是Storage的工作方式)
getImages: function(uid, images) {
images.forEach((filename) => {
var ref = firebaseApp.storage().ref('images/' + uid + "/" + filename);
ref.getDownloadURL().then(function(url) {
this.finalImages.push(url)
console.log(url);
}).catch(function(error) {
switch (error.code) {
case 'storage/object_not_found':
// File doesn't exist
console.log('Object not found');
break;
case 'storage/unauthorized':
// User doesn't have permission to access the object
console.log('You do not have the right permissions');
break;
case 'storage/canceled':
// User canceled the upload
console.log('Canceled');
break;
case 'storage/unknown':
// Unknown error occurred, inspect the server response
console.log('Who knows...');
break;
}
})
})
}
但是URL在代码完成之后下载,所以我再也看不到它们。如何停止所有操作并等待URL在finalImages
数组中出现然后继续?
答案 0 :(得分:1)
您可以将每个请求映射到一个承诺,然后等待所有承诺完成:
getImages: function(uid, images) {
Promise.all(images.map((filename) => {
return new Promise((resolve, reject) => {
var ref = firebaseApp.storage().ref('images/' + uid + "/" + filename);
ref.getDownloadURL().then(function(url) {
resolve(url);
}).catch(function(error) {
// Uncomment this line to ignore errors.
reject(error);
switch (error.code) {
case 'storage/object_not_found':
// File doesn't exist
console.log('Object not found');
break;
case 'storage/unauthorized':
// User doesn't have permission to access the object
console.log('You do not have the right permissions');
break;
case 'storage/canceled':
// User canceled the upload
console.log('Canceled');
break;
case 'storage/unknown':
// Unknown error occurred, inspect the server response
console.log('Who knows...');
break;
}
})
});
})).then((finalImages) => {
// all images.
})
}