Прямо сейчас этот раздел кода передается undefined в if (customerWaiting >0). Это проблема с async, которую я не могу понять.
Судя по другим темам, на которые я смотрел, это очень простой вопрос для новичков, я просто не могу заставить его работать.
Я смотрел, сможешь ли ты найти это для меня
Изменить 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.info("There are " + snapshot.numChildren() + " customers waiting");
});
ref.child("employeeWaiting").on("value", function(snapshot) {
var employeeWaiting = snapshot.numChildren();
console.info("There are " + snapshot.numChildren() + " employees waiting");
});
}
if (customerWaiting > 0) {
$("#myModal").modal();
console.info("connect");
} else {
console.info("There are " + customerWaiting + " employees waiting");
console.info("no connect");
}
});
Это потому, что customerWaiting определяется только в обработчиках событий value, а не в вашем внешнем обработчике click. Трудно понять, чего именно вы здесь пытаетесь достичь, но я могу сказать вам, что вложенные обработчики событий почти всегда - плохая идея. Не могли бы вы более подробно объяснить свою цель, а также код, который вы используете.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Если я правильно вас понял, вы хотите сделать следующее:
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.info("There are " + snapshot.numChildren() + " customers waiting");
if (customerWaiting > 0) {
// show the modal if customerWaiting > 0
$("#myModal").modal();
console.info("connect");
} else {
console.info("There are " + customerWaiting + " employees waiting");
console.info("no connect");
}
});
});
Если вы хотите использовать await / async, тогда ref.child("customerWaiting").on("value", resolve) должен поддерживать обещания, или вам нужно преобразовать его в один:
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.info("There are " + snapshot.numChildren() + " customers waiting");
if (customerWaiting > 0) {
$("#myModal").modal();
console.info("connect");
} else {
console.info("There are " + customerWaiting + " employees waiting");
console.info("no connect");
}
});
customerWaitingобъявлен локально, но используется глобально (в обратном вызове щелчка).