我的用例是获取服务器时间并提取day-month-year(10-12-2019),然后编写/更新。由于将日-月-年作为文档ID。但是通过使用以下代码,可以为每个snapshot.data()。timestamp值添加第一个null?
getServerTime(){
var db = firebase.firestore();
var ref = db.collection("ServerTimeStamp").doc("time");
ref.set({ timestamp: firebase.firestore.FieldValue.serverTimestamp() });
ref.onSnapshot(async function(snapshot) {
var timestamp = snapshot.data().timestamp;
console.log(timestamp); // here first coming NULL then actual vaku
})
}
第一个快照回调为您提供null的原因是,先前的写入尚未完成。稍后会得到一个时间戳,因为在写操作完成后,侦听器将再次被触发。
对set()
的调用是异步的,并在完成之前立即返回。它返回一个promise,您应使用该promise来确定何时完成。如果您的目标是获取服务器时间戳,我建议使用该承诺等待写入完成,然后使用get()
再次取回文档(不要使用侦听器)。
请注意,获得时间戳记的那一刻会及时延迟,因为您的代码将等待服务器的响应,因此无法保证实际花费的时间。
此代码正确运行,但是是最佳方法吗?
getServerTime(){
var db = firebase.firestore();
var ref = db.collection("ServerTimeStamp").doc("time");
ref.set({ timestamp: firebase.firestore.FieldValue.serverTimestamp()});
ref.get().then(a=>{
console.log(a['_document'].data.internalValue.root.value);
})
}
任何人都可以推荐更好的方法吗?