0

I am using a function to query firebase realtime database and get required information. The information is stored in an array which is returned.

The challenge is that function returns the array even before database fetches the record and so I get empty result. As I need to use .on to fetch multiple records, I cannot use .then with the query.

How can I ensure that va_addresses is returned after query is fully executed.

const getAddressLabel = (vp_userid) => {
    let vo_obj;
    let va_addresses = [];

    firebase
        .database()
        .ref("address/" + vp_userid)
        .orderByKey()
        .on("child_added", function (snapAddress) {
            vo_obj = {
            label: snapAddress.val().addresslabel,
            value: snapAddress.val().addresslabel,
            };
            va_addresses.push(vo_obj);
        });
    return va_addresses;
};
nakhouri
  • 41
  • 5
  • Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) and [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) – Nick Parsons May 30 '21 at 10:29

1 Answers1

0

To get the expected result try not to use a listener because you want to return the data. You would need to get the data only once so we use .once('value'):

const getAddressLabel = async (vp_userid) => {
  let vo_obj;
  let va_addresses = [];

  const snapAddress = await firebase
    .database()
    .ref("address/" + vp_userid)
    .orderByKey()
    .once("value");

  vo_obj = {
    label: snapAddress.val().addresslabel,
    value: snapAddress.val().addresslabel,
  };

  va_addresses.push(vo_obj);

  return va_addresses;
};

Just be careful when using getAddressLabel because that one will be an async function now.

Tarik Huber
  • 7,061
  • 2
  • 12
  • 18
  • Thank you for your suggestion. I had to use .on because this query fetches multiple records. If I use .once, I suppose it will capture only first row. – nakhouri May 31 '21 at 12:36
  • `.on` is a listener. Her will give you live updates when the data changes. `.once` is there to get the data once but it will give you all the data. The only difference is that one is a live listener and the other gets the data once. – Tarik Huber May 31 '21 at 13:25