'getDownloadURL' 在承诺中少返回一个 URL



我正试图将几张照片上传到Firebase Storage,并获取它们的URL,将它们作为字段添加到健身房的个人资料中。然而,对于我提出的代码,总是有一个URL没有返回。如果我上传3张图片,3张图片会出现在存储中,但我只得到2个URL。我该怎么解决?

const promises = [];
const URLarray = [];
imageAsFile.forEach(img => {
const uploadTask = storage.ref().child(`/photos/${doc.id}/${img.name}`).put(img);
promises.push(uploadTask);
uploadTask.then((uploadTaskSnapshot) => {
return uploadTaskSnapshot.ref.getDownloadURL();
}).then((pic) => {
const addPics = db.collection("gyms").doc(doc.id)
promises.push(addPics);
addPics.update({gymPhoto: firebase.firestore.FieldValue.arrayUnion(pic)});
// URLarray.push(pic)
})
});
Promise.all(promises).then(() => {
// console.log(URLarray)
alert("Done");
})

以下内容应该有效(未经测试(:

const promises = [];
imageAsFile.forEach(img => {
const uploadTask = storage.ref().child(`/photos/${doc.id}/${img.name}`).put(img);
promises.push(uploadTask);
});
Promise.all(promises)
.then(uploadTaskSnapshotsArray => {
const promises = [];
uploadTaskSnapshotsArray.forEach(uploadTaskSnapshot => {
promises.push(uploadTaskSnapshot.ref.getDownloadURL());
});
return Promise.all(promises);
})
.then(urlsArray => {
const docRef = db.collection("gyms").doc(doc.id);
return docRef.update({ gymPhoto: firebase.firestore.FieldValue.arrayUnion(...urlsArray) });
})

Promise.all()返回一个promise:此promise通过一个数组来实现,该数组包含作为参数传递的数组中的所有已解析值。

因此,如果您使用uploadTasks的数组调用Promise.all(),当返回的承诺实现时,您将获得uploadTaskSnapshots的数组。

然后,您需要再次使用Promise.all()使用此数组来获取URL数组。

然后,当您获得URL数组时,您只需要更新一次id为doc.id的文档。因此,在这里您不需要Promise.all()。您需要做的是将几个值传递给FieldValue.arrayUnion()方法。为此,您需要使用排列运算符,如下所示:

docRef.update({ gymPhoto: firebase.firestore.FieldValue.arrayUnion(...urlsArray) });

最新更新