1
votes

I am trying to send data from my firebase database back to my client in a cloud function. I want to return the entire json child object. Here is the code for my cloud function:

exports.addNumbers = functions.https.onCall((data, context) => {
 admin.database().ref('store/ingredients').once('value', function(snapshot) {
    
    return snapshot.val();

  });

});

Here is my client code that is invoking this cloud function and accessing its data:

const addNumbers = firebase.functions().httpsCallable('addNumbers');
  addNumbers().then(result => {
    console.log(result.data + "in client");
  });

But the data returned in the client is null and the cloud function is returning only object [Object] in the firebase logs. Please someone help me.

1

1 Answers

1
votes

You're almost there. You just need to return something from the top-level code in your Cloud Function.

The easiest way is to use a then clause:

exports.addNumbers = functions.https.onCall((data, context) => {
  return admin.database().ref('store/ingredients').once('value').then((snapshot) => {
    return snapshot.val();
  });
});

Now the value from the database "bubbles up" to the calling code, and is then returned out of your function as a promise.


On modern JavaScript versions, you can make this code easier to read by using async/await:

exports.addNumbers = functions.https.onCall(async (data, context) => {
  let snapshot = await admin.database().ref('store/ingredients').once('value')
  return snapshot.val();
});

This works exactly the same under the hood (it's really just syntactic sugar), but most developers find it much easier to read.