Home > Software engineering >  If I use `.push();` to crate a new empty Firebase realtime DB datum, do I have to resolve the promis
If I use `.push();` to crate a new empty Firebase realtime DB datum, do I have to resolve the promis

Time:08-27

I inherited some NodeJs code which repeatedly uses .push(); to create a new empty array (node/leaf/whatever the FB terminology is - but, it's an array/list).

Immediately afterwards the code loops and starts writing entries to it.

On the one had I am nervous because it looks like a code smell and the quality of the code is noticeably amateurish even to me - and I am primarily an embedded C guy.

The code properly treats reads as async and waits for the promise to resolve:

admin
  .database()
  .ref(url)
  .once("value", (snapshot) => { ...

but, the pushes do not wait.

My big fear is that the request to write an array member could arrive at FB before the array has been created, and timing bugs like that are the absolute worst to debug.

On the other hand, this is done so consistently that the original coder may know something that I do not.

Does the code have a problem?

CodePudding user response:

Seeing the actual code that you're asking about would be useful, but my guess is that you have something like:

newRef = rootRef.push();
newRef.set('some value');

That first line does not actually write anything to the database yet. In fact, it is a purely client-side operation that just creates a new unique ID and returns a reference to that.

So there's no need to await the call in that first line as it is synchronous.


The two lines could be combined into:

rootRef.push('some value');

Now the push() operation does perform the write to the database and if you want to perform another operation after the write, you would have to await it.

  • Related