0

In firebase documentation I didn't find a simple way to get data from firebase db - only by events (.on, .once). Is this the only way?

In this case, to get data from different branches, I need to describe handler in handler? And response.send() must be in deepest handler?

Is this the correct function?

exports.test = functions.https.onRequest((request, response) => {
var db = admin.database();

db.ref("test/val").once("value", snap => {
    var val1 = snap.val();
    db.ref("test/val").set(val1+1);
    db.ref("test2/val").once("value", snap => {
        var val2 = snap.val();
        response.send(val1+", "+val2);
    });
});

//response.send("bad way");
});

1 Answer 1

2

You're close, but you need to make sure you wait for all asynchronous work to complete (your set does not get waited on). I've reworked it a bit to use promises instead of callbacks to make the flow clear:

exports.test = functions.https.onRequest((request, response) => {
  var db = admin.database();

  var val1, val2;
  db.ref("test/val").once("value").then(snap => {
    val1 = snap.val();
    return db.ref("test/val").set(val1+1);
  }).then(() => {
    return db.ref("test2/val").once("value');
  }).then(snap => {
    val2 = snap.val();
    response.send(val1+", "+val2);
  }).catch(err => {
    console.log(err);
    response.send("error occurred");
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.