我将文件保存到Google云端存储后尝试更新Firestore文档。我想将存储文件的URL数组发送到Firestore中的文档,如下所示......
(attachments: [ {url: "fileone.jpeg", ...}, {url: "filetwo.jpeg", ...}, ...]).
通过使用firebases getDownloadURL()
在前端创建此URL数组。我可以成功更新我的文档,但更新文档中的数组总是比前端创建的数组少一个项目。当console.log
存储在内存中的数组(发送到firestore)时,我发现在[{},{}]
之前的括号内的值也比array.length少一个。
记录fileUrls数组(存储在内存中以发送到firestore)的控制台显示,即使fileUrls.length === 3
和扩展下面的行显示从索引0开始的所有三个包含URL的对象:
fileUrls: > (2) [{…}, {…}]
以下是实施此更新过程的代码:
let fileUrls = []; // <<-- Array for file urls to be stored
let promises = [];
for (const file of state.post.files) {
const fileRef = storage.ref().child(`my file path`);
const p = fileRef.put(file)
.then(snapshot => {
fileRef.getDownloadURL()
.then(url => {
fileUrls.push({ url: url, type: file.type }) // Adding urls to arr
})
})
promises.push(p);
}
const all = Promise.all(promises);
all
.then(() => {
submissionRef.update({ // <<<--- Updating document created prior.
attachments: fileUrls
})
})
.catch(err => console.log(err));
您正在等待文件完成上传,但您不会等到获取下载URL。您需要将getDownloadURL返回的承诺包含在传递给Promise.all()的promise数组中。尝试从then
回调中返回其承诺,以便上传文件:
const p = fileRef.put(file)
.then(snapshot => {
// add a return here to chain the promise returned by getDownloadURL()
// with the promise returned by put()
return fileRef.getDownloadURL()
.then(url => {
fileUrls.push({ url: url, type: file.type }) // Adding urls to arr
})
})
请考虑使用async / await语法来避免所有这些回调并使代码更易于阅读。