Tuesday, 7 May 2019

What is the sequence of events that happens when I'm using set() in Firebase?

My code below attempts to insert a Timestamp into Firebase. The Timestamp I'm referring to is this one here. I plan to retrieve the inserted Timestamp and convert said Timestamp to a Date JS Object to be displayed when a user requests for said time. I tried retrieving said Timestamp and encountered something rather strange to me.

I have the following code, initially:

let newRef = firebase.database().ref().child('fs').push(); //'fs' here is one of the nodes in my Firebase

newRef.set({
  //Set some other data
  timeCreated: firebase.database.ServerValue.TIMESTAMP
}).then(() => {
  console.log('Insert successful');
});

newRef.once('value').then((snapshot) => {
  console.log(snapshot.val().timeCreated);
  console.log(new Date(snapshot.val().timeCreated));
});

I soon noticed that I was breaking my chain of Promise. Because of that, I changed it into the following:

let newRef = firebase.database().ref().child('fs').push();

newRef.set({
  //Some other data
  timeCreated: firebase.database.ServerValue.TIMESTAMP;
}).then(() => {
  console.log('Insert successful');
  return newRef.once('value').then((snapshot) => snapshot.val().timeCreated);
}).then((timeRetrieved) => {
  console.log(timeRetrieved);
  console.log(new Date(timeRetrieved);
});

And it retrieved the correct data.

My confusion is at the initial code. Why does Firebase still somehow successfully retrieved timeCreated when the process of set() hasn't been completed? I looked at the console.log(...) and the first one to appear is the reading data process. However, as Firebase hasn't even set the value of timeCreated, shouldn't I be reading a null or some other null-like value? Instead, the reading data code returned a Timestamp that is slightly smaller in value to the Timestamp that is to be set().

EDIT

As per request, these are the results I get using my initial code:

Result

However, the value of timeCreated stored in my Firebase is: 1556862732784, which is different from the result of the image above (the result of the image above is the result of console.log(snapshot.val().timeCreated) [1556862732273]).



from What is the sequence of events that happens when I'm using set() in Firebase?

No comments:

Post a Comment