现在,此部分代码未定义传递到if(customerWaiting >0)
。我似乎无法弄清楚这是异步的问题。
基于我看过的其他线程,这是一个非常基本的问题,也是一个新手问题,我无法使其正常工作。
我在看你是否能找到我
编辑1:
代码的目标是查看firebase“ customerWaiting”数据库中是否有客户,如果有,则显示模式,如果没有,则表明没有客户在等待
structure for database is
customerWaiting
-Automatically generated ID
-customer information
这是代码
var customerWaiting;
var employeeWaiting;
var ref = firebase.database().ref();
$("#connectNextUser").click(function() {
{
ref.child("customerWaiting").on("value", function(snapshot) {
var customerWaiting = snapshot.numChildren();
console.log("There are " + snapshot.numChildren() + " customers waiting");
});
ref.child("employeeWaiting").on("value", function(snapshot) {
var employeeWaiting = snapshot.numChildren();
console.log("There are " + snapshot.numChildren() + " employees waiting");
});
}
if (customerWaiting > 0) {
$("#myModal").modal();
console.log("connect");
} else {
console.log("There are " + customerWaiting + " employees waiting");
console.log("no connect");
}
});
答案 0 :(得分:3)
如果我对您的理解正确,那么您想这样做:
var ref = firebase.database().ref();
$("#connectNextUser").click(function() {
// query how many customers are waiting
ref.child("customerWaiting").on("value", function(snapshot) {
// as soon as you have the result then get the numChildren
var customerWaiting = snapshot.numChildren();
console.log("There are " + snapshot.numChildren() + " customers waiting");
if (customerWaiting > 0) {
// show the modal if customerWaiting > 0
$("#myModal").modal();
console.log("connect");
} else {
console.log("There are " + customerWaiting + " employees waiting");
console.log("no connect");
}
});
});
如果您想使用await
/ async
,那么ref.child("customerWaiting").on("value", resolve)
必须支持Promises,或者您需要将其转换为一个:
var ref = firebase.database().ref();
$("#connectNextUser").click(async function() {
var snapshot = await new Promise((resolve, reject) => {
ref.child("customerWaiting").on("value", resolve)
// you should also handle the error/reject case here.
})
var customerWaiting = snapshot.numChildren();
console.log("There are " + snapshot.numChildren() + " customers waiting");
if (customerWaiting > 0) {
$("#myModal").modal();
console.log("connect");
} else {
console.log("There are " + customerWaiting + " employees waiting");
console.log("no connect");
}
});