javascript If/Else循环;异步问题

javascript If/Else循环;异步问题,javascript,jquery,asynchronous,async-await,Javascript,Jquery,Asynchronous,Async Await,现在,这段代码正在传递给未定义的if(customerWaiting>0)。这是async的一个问题,我似乎无法理解 根据我看到的其他线程,这是一个非常基本的新手问题,我就是不能让它工作 我在看你能不能帮我找到 编辑1: 代码的目标是查看firebase“customerWaiting”数据库中是否有客户,如果有,则显示模式,如果没有,则表示没有客户在等待 structure for database is customerWaiting -Automatically generat

现在,这段代码正在传递给未定义的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.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");
  }
});

如果我理解正确,您希望这样做:

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");
    }
  });
});
如果要使用
wait
/
async
,则
ref.child(“customerWaiting”)。在(“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.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");
  }
});

customerWaiting
在本地声明,但全局使用(在单击回调中)。这是因为
customerWaiting
仅在
value
事件处理程序中定义,而不是外部
单击
handler。很难确切理解您在这里想要实现什么,但我可以告诉您,嵌套事件处理程序几乎总是一个坏主意。你能提供一个更详细的解释你的目标,以及你正在使用的代码。