shapiro yaacov
shapiro yaacov

Reputation: 2346

Firebase updating with node.js - do I need to await?

Scenario:

Some code is listening on collection A for changes. When one occurs, it does some calculation and updates collection B.

Time between changes in A: 20-50ms. Time for actual calculation: 20-30ms. Time for roundtrip sending updates to firebase: 250-300ms.

So the code is something like this:

const runUpdates = async (snapshot) => {
  const inputData = snapshot && snapshot.exists() && snapshot.val() || undefined
  if (inputData) {
    const calculatedData = calculateStuff(inputData)
    await firebase.database().ref().update({ 'collectionB': calculatedData })
  }
}

firebase.database().ref('collectionA').on('value', runUpdates)

I'm using Firebase Realtime Database.

Actual question:

Does the firebase package (using local cache or any other means necessary) assure that the updates will be done in firebase in the same order that I have done them in my code or do I need to await for every update to finish before I can move on to my next computation & update?

More details:

There is a mechanism in place for cases when there is a trigger event but the calculation/update is not yet finished. I'm porpusfully ignoring that or clarity.

I'm trying to improve this code and it seems that in many cases the calculation is relatively short, but then I need to wait for the response from firebase to start the next calculation.

I've been told that firebase has a local cache (server-side) and that my firebase update command actually updates that locally (and therefore is "immediate") and then works to propagate the change to firebase itself. Any sequential updates would also be propagated, while the sequence is assured.

(Needless to say, I tried looking around for this info in the docs etc)

Upvotes: 2

Views: 835

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317362

Queries to Realtime Database are pipelined over a single socket connection. The results will be delivered in the order that the queries were issued.

If you need to know when the results of write have been fully committed to the server, you will need to pay attention to the promise returned by update(). That promise will become fulfilled only after the write completes on the server, and not when changes are available just locally.

Whether your use await or then on that promise doesn't really matter. Either way, you will know the result of the update.

Upvotes: 3

Related Questions