简体   繁体   中英

Is there a way to get the actual timestamp when using firebase.database.ServerValue.TIMESTAMP?

This question is about the javascript client.

I have code that goes something like this:

const localEvents = [];
const fbEvents = firebase.database().ref("myevents");

fbEvents.on("child_added", function(snapshot) {
  const e = snapshot.val();
  localEvents.push(e);
});

function createEvent(e) {
  e.time = firebase.database.ServerValue.TIMESTAMP;
  fbEvents.push(e);
}

After calling createEvent({}) , it appears that entries in my localEvents list have time values which are not equal to the actual entries in the database (the client guesses the timestamp and calls the child_added handler before it's actually done a roundtrip to the server). Is there any way to avoid this, and/or is there any way to get a callback when the actual value of the time is known?

It's not possible, using only the snapshot in the listener, to determine if the timestamp comes from the server or is guessed locally.

What you can do instead is use the promise returned from fbEvents.push(e) to determine when the write actually succeeds. A resolved promise which means it was definitely written to Firebase. The listener callback you get after that will contain the server's updated value.

(Note that with Firestore it is possible to determine if a document was fully written to the server or not. Just not with Realtime Database.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM