我正在嘗試從 firebase 實時資料庫中獲取資料。我知道如何獲取資料,我可以記錄它,但它沒有回傳。如果我在代碼中的其他任何地方使用該函式將該資料設定為變數,它總是回傳未定義。
function getData(target) {
const reference = ref(db, `${target}/`);
onValue(reference, (snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val());
return snapshot.val();
}
});
}
console.log(snapshot.val());作品_
我嘗試了很多解決方案,但無法讓它按照我想要的方式作業。基本上,我想從 firebase 獲取資料并使其發揮作用,這樣我就可以在我的其他檔案中使用它,只需傳遞一個資料庫參考。一切正常,除了它不回傳該值。
uj5u.com熱心網友回復:
聽起來您只想讀取一次資料,您可以這樣做get():
function getData(target) {
const reference = ref(db, `${target}/`);
return get(reference).then((snapshot) => {
if (snapshot.exists()) {
return snapshot.val();
}
// TODO: what do you want to return when the snapshot does *not* exist?
});
}
或與async/await
async function getData(target) {
const reference = ref(db, `${target}/`);
const snapshot = get(reference);
if (snapshot.exists()) {
return snapshot.val();
}
// TODO: what do you want to return when the snapshot does *not* exist?
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/456690.html
標籤:javascript 火力基地 功能 异步 firebase-实时数据库
上一篇:使用Swift中的新異步任務從另一個執行緒正確訪問核心資料
下一篇:該流當前正被先前的操作使用
