Home > Mobile >  how to return data through function when fetching data from firebase realtime-database in node.js
how to return data through function when fetching data from firebase realtime-database in node.js

Time:10-19

How can I get this key in DATA and use this key outside of the function?

let DATA = [];

  const database = admin.database();
  let keyref = database.ref("data");

  keyref.once("value", async function (snapshot) {
    let key = await snapshot.val(); // i want this key data out side this function
    DATA.push(key);
    console.log(DATA);
  });

 console.log(DATA); // i want here that inside function key

In short, I want fetched data outside the function

CodePudding user response:

When fetching RTDB data only once, it is advised to use the get() method. This method is asynchronous, so you need to do something along the following lines:

  async function getRTDBData(ref) {
    const database = admin.database();
    const keyref = database.ref("data");
    const snapshot = await keyref.get();

    if (snapshot.exists()) {
        return snapshot.val();
    } else {
       return .... // Up to you to adapt here
    }
  }

  getRTDBData("data")
  .then(val => {
      // Do what you want with val
      cosniole.log(val);
  })
  • Related