Handling Asynchronous Calls (Firebase) in functions

firebase functions async/await
firebase async/await
firebase asynchronous android
firestore async/await
firebase synchronous read
firebase cloud functions promises
wait until firebase retrieve data android
firebase promise

Several times now I have run into an issue with synchronous & asynchronous functions using Firebase. My problem is often that I need to make an asynchronous Firebase call within a function that I wrote. As a simple example, suppose I need to calculate & display the velocity of an object, and my Firebase stores distance & time:

function calcVelocity() {
    var distance, time, velocity;

    firebaseRef.once('value', function(snapshot) {
        distance = snapshot.val().distance;
        time = snapshot.val().time;

        velocity = distance / time;
    });
    return velocity;
}

$("#velocity").html(calcVelocity());

Of course, the above code will not work because firebaseRef.once() is an asynchronous call, so velocity has not been set yet when we reach return velocity;. If we place the return inside the .on() callback function, then nothing is returned at all.

One solution would be to make my calcVelocity() function asynchronous as well.

Another solution would be to store a cached version of the Firebase that is read synchronously but updated asynchronously from the Firebase.

Is one of these solutions better than the other? And is there a better solution?

You nailed the two possibilities: Either make your function asynchronous as well, or cache the latest Firebase data so you can access it synchronously. Which one you use is just a matter of preference and convenience, given the context of the app you're writing.

For instance, we've noticed that "action games" are usually driven by a tight render loop instead of by firebase data change events. So it makes sense to cache the latest Firebase data for use in your render loop. For example:

var latestSnapshot = null;
firebaseRef.on('value', function(snap) { latestSnapshot = snap; });

And then you can use latestSnapshot synchronously in your render loop (or wherever else), though you need to be careful to deal with it being null until the first firebase callback happens.

Retry asynchronous functions, describes how you can request asynchronous (non-HTTPS) background functions to retry on failure. Deal with duplicate function calls out-of-band. Several times now I have run into an issue with synchronous & asynchronous functions using Firebase. My problem is often that I need to make an asynchronous Firebase call within a function that I

Another approach is to utilize a Promise strategy. jQuery has a great one.

function calcVelocity() {
    var distance, time, velocity, def = $.Deferred();

    firebaseRef.once('value', function(snapshot) {
        distance = snapshot.val().distance;
        time = snapshot.val().time;

        def.resolve( distance / time );
    });
    return def.promise();
}

calcVelocity().then(function(vel) { $("#velocity").html(vel); });

Keep in mind also that snapshot.val().distance; may return an error if snapshot.val() returns null!

Handling Asynchronous Calls (Firebase) in functions, You nailed the two possibilities: Either make your function asynchronous as well, or cache the latest Firebase data so you can access it synchronously. Which one you use is just a matter of preference and convenience, given the context of the app you're writing. The Firebase Unity SDK makes judicious use of asynchronous logic for many of its calls. Unity itself isn’t super resilient to threaded logic, with most of the classes and functions in the UnityEngine namespace just flat out throwing exceptions if invoked off of the main Unity thread.

Same idea as in the answer @Kato provided, but with the built-in promises in Firebase would look something like this

function calcVelocity(snapshot) {
    var distance, time, velocity;

    distance = snapshot.val().distance;
    time = snapshot.val().time;

    return distance / time;
}

function getVelocity() {
return firebaseRef.once('value').then(calcVelocity);
}

getVelocity().then(function(vel) { $("#velocity").html(vel); });

Why are the Firebase API asynchronous?, Firebase APIs are sensitive to the performance of your app's main thread. This means that any Firebase API that needs to deal with data on disk or network is implemented in an asynchronous style. The functions will return immediately , so you can call them on the main thread without worrying about performance. Firebase APIs are sensitive to the performance of your app’s main thread. This means that any Firebase API that needs to deal with data on disk or network is implemented in an asynchronous style.

Use async/await with TypeScript in Cloud Functions for Firebase , Using async/await syntax with Cloud Functions for Firebase can make your TypeScript and Duration: 6:10 Posted: Jun 7, 2018 The function cannot reach a service endpoint, or times out while trying to reach the endpoint. The function intentionally throws an exception (for example, when a parameter fails validation). When functions written in Node.js return a rejected promise or pass a non-null value to a callback.

Firebase Functions Tutorial #17 - Async & Await, Hey gang, in this firebase functions tutorial we'll take a look at how we can use async and Duration: 4:35 Posted: Mar 24, 2020 Firebase has an impressive feature list for getting your apps up and running quickly. I love that I can go from idea to working app in a matter of hours! But for developers who haven't had much experience with asynchronous programming, it's easy to get bogged down in the details. Heck, I've been working with Firebase for two years and I still find myself pausing to think about how I want to

Swift Closures and Firebase, Instead, I want to get into how to get a function that uses an async callback working the way you want it to in Swift. Take this example function I� The Cloud Functions for Firebase client SDKs let you call functions directly from a Firebase app. To call a function from your app in this way, write and deploy an HTTPS Callable function in Cloud Functions, and then add client logic to call the function from your app.

Comments
  • possible duplicate of JavaScript asynchronous return value / assignment with jQuery -- yes, make calcVelocity accept a callback or return a deferred object.
  • Good idea - I didn't think about just caching the snapshot.
  • Saved my day! Event after 4 years !
  • it makes calVelocity() syncronous function?
  • Not in the least. It uses a promise which resolves when the data is available.
  • so it resembles $loaded in angularfire
  • Nice! Promises were added a little after 2012. Made one quick edit, as you were prematurely invoking calcVelocity (with an undefined value).