【问题标题】:how to return data through function when fetching data from firebase realtime-database in node.js从node.js中的firebase实时数据库获取数据时如何通过函数返回数据
【发布时间】:2021-12-06 06:52:42
【问题描述】:

如何在 DATA 中获取此密钥并在函数外使用此密钥?

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

简而言之,我想在函数外获取数据

【问题讨论】:

    标签: javascript node.js firebase express firebase-realtime-database


    【解决方案1】:
    async function getData() {
      console.log("Refreshing Firebase Credentials");
      const keyref = database.ref("data");
      const snapshot = await keyref.get();
    
      if (snapshot.exists()) {
        const snapshotVal = snapshot.val();
        console.log(snapshotVal);
        credentials = {
          expires_at: new Date(snapshotVal.expires_at),
          enc_key: snapshotVal.enc_key,
          iv: snapshotVal.iv,
        };
      } else {
        console.log("Firebase Credentials not found");
        process.exit(1);
      }
    }
    
    module.exports = {
      getData
    };
    

    在你想要这个数据的地方使用这个函数

    【讨论】:

      【解决方案2】:

      当只获取一次 RTDB 数据时,建议使用get() 方法。此方法是异步的,因此您需要按照以下方式进行操作:

        async function getRTDBData(ref) {
          const database = admin.database();
          const keyref = database.ref(ref);
          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
            console.log(val);
        })
      

      【讨论】:

      • 谢谢 Renaud Ternec,你让我的一天爱你,兄弟...
      • 先生,我如何将这个 snapshot.val() 存储在功能之外,因为我想全局存储该值。在全局存储后,我想在 getRTDBData 中使用。
      • 您只能在then 块中这样做,因为该函数是异步的。
      • 好的,先生,让我试试看
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多