javascript If / Else Loop;асинхронная проблема - PullRequest
0 голосов
/ 15 декабря 2018

Прямо сейчас этот раздел кода проходит неопределенно до if(customerWaiting >0).Это проблема асинхронности, которую я не могу понять.

Судя по другим темам, на которые я смотрел, это очень простой вопрос и вопрос новичка, я просто не могу заставить его работать.

Я проверял, можете ли вы найти его для меня

Редактировать 1:

цель кода - увидеть, есть ли клиенты в базе данных firewase "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");
  }
});

1 Ответ

0 голосов
/ 15 декабря 2018

Если я правильно вас понимаю, вы хотите сделать это:

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) должен поддерживать Обещания, или вам нужно преобразовать егок одному:

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");
  }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...