![](/img/trans.png)
[英]how to return data through function when fetching data from firebase realtime-database in react native
[英]how to return data through function when fetching data from firebase realtime-database in node.js
如何在 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
简而言之,我想在函数之外获取数据
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
};
在您想要此数据的地方使用此功能
当只获取一次 RTDB 数据时,建议使用get()
方法。 此方法是异步的,因此您需要按照以下几行做一些事情:
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);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.