kkost
kkost

Reputation: 3730

Cloud Functions for Firebase: how to read data from Database synchronously?

I using Cloud Functions for Firebase to build HTTP endpoint. Inside this endpoint I am trying to read some data from Firebase Realtime Database synchronously by this method:

function getSomethingFromDbSynchronously (currency) {
    return new Promise((resolve, reject) => {
        var db = admin.database();
        var ref = db.ref("someref");
        ref.orderByChild("somechild").equalTo("something").once("value", function (snapshot) {
            resolve(snapshot);
        });
    });
}

But it is doesn't works for me. My API route returns by the first return statement before this request to the DB ends. What am I do wrong ?

Upvotes: 0

Views: 995

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

The code looks fine: you're creating a new promise and returning that from getSomethingFromDbSynchronously(). But the code that calls getSomethingFromDbSynchronously() will then need to wait for the promise to resolve, with something like:

getSomethingFromDbSynchronously("currency").then(function(snapshot) {
  console.log(snapshot.val());
});

There is no way to make this synchronous, although you could look into the new async and await keywords, which simply make the above read as if it happens synchronously.

Note, that your code is a bit longer than needed. Since once() already returns a promise, you might as well return that directly:

function getSomethingFromDbSynchronously (currency) {
    var db = admin.database();
    var ref = db.ref("someref");
    return ref.orderByChild("somechild").equalTo("something").once("value");
}

Upvotes: 2

Related Questions