在下面的代码中,我得到一个文档,更新它,然后尝试使用更新中的数据,但会记录undefined
。为什么会这样,以及如何等待从文档中成功获取新数据。
db.collection("collection").doc("docid").get().then(doc =>
doc.ref.update({ message: "hello" }).then(() => console.log(doc.data().message));
)
我正在使用firebase的Javascript Web版本。
如果我理解正确,您需要等待更新完成,然后再继续代码。在DocumentReference
上调用update
会返回一个解析为WriteResult
的promise。你可以简单地等待承诺得到解决,然后继续使用代码:
// store DocumentReference
const docRef = db.collection("collection").doc("docid");
// update document
docRef.update({ message: "hello" }).then(writeResult => {
// wait for update to complete and display WriteResult
console.log(writeResult);
// to prove that update is finished, fetch the same document from firestore
return docRef.get();
}).then(documentSnapshot => {
console.log(documentSnapshot.id, "=>", documentSnapshot.data());
// => "docid => { message: 'hello'}"
})
与ASYNC AWAIT语法相同的解决方案
// store DocumentReference
const docRef = db.collection("collection").doc("docid");
// update document + wait for completing, then display write result
const writeResult = await docRef.update({ message: "hello" });
console.log(writeResult);
// to prove that update is finished, fetch the same document from firestore
// and display document content
const documentSnapshot = await docRef.get();
console.log(documentSnapshot.id, "=>", documentSnapshot.data());
// => "docid => { message: 'hello'}"