我有一个 Firebase 查询。
由于 Firebase 异步工作,因此该函数将继续运行,而无需等待 Firebase 检索值。
有没有办法等待 Firebase 查询的结果,然后才从函数返回?
function CheckBuyingCondition(prefix) {
var Res = "";
var Current_Price_Open_ref = firebase.database().ref("dailyT/Current_Price_Open/" + nextDayTrading).orderByChild("Prefix").equalTo(prefix)
Current_Price_Open_ref.once("value").then(function(snapshot) {
if(snapshot.exists()) {
snapshot.forEach(function(childSnapshot) {
var val = childSnapshot.val();
res = "" + val.Current_Price_Open;
});
}
else {
res = "NA";
}
});
return res; // (Here I got res = "" instead of the correct value from Firebase query
}
最佳答案
使用异步/等待
:
async function checkBuyingCondition(prefix) {
var res = '';
var currentPriceOpenRef = firebase.database()
.ref(`dailyT/currentPriceOpen/${nextDayTrading}`)
.orderByChild('prefix')
.equalTo(prefix);
var snapshot = await currentPriceOpenRef.once('value');
if(snapshot.exists()) {
snapshot.forEach(function(childSnapshot) {
var val = childSnapshot.val();
res = `${val.currentPriceOpen}`;
});
} else {
res = 'NA';
}
return res;
}
请注意,这根本不会使您的函数同步,因此在函数声明开头使用 async
关键字;它只是让你的函数看起来像一个。
在函数内的第三行,您会注意到 await
关键字。这会等待您的 promise 解决,然后返回结果,在您的情况下,该结果是来自 Firebase 的快照。您只能在 async
函数中使用 await
。
关于javascript - 如何等待 Firebase 检索值然后退出该函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48934280/