保存数据时等待Firebase响应

时间:2019-01-09 19:20:01

标签: javascript html5 firebase firebase-realtime-database

我正在将表单数据保存到Firebase,我想等待成功再显示警报。我该如何实现?我正在使用以下代码:

var submitInquiry = function () {
  // Get input values from each of the form elements
  var name = $("#student-name").val();
  var contact = $("#student-contact").val();
  var email = $("#student-email").val();
  var board = $("#student-board").val();
  var subject = $("#student-subject").val();
  var standard = $("#student-class").val();
  var message = $("#student-message").val();

  // Push a new inquiry to the database using those values
  var inquiryInstance =  inquiry.push();
  inquiryInstance.push({
    "name": name,
    "contact": contact,
    "email": email,
    "board": board,
    "subject": subject,
    "standard": standard,
    "message": message,
  }); 

  alert("Thank You! Your request has been received and our team will connect with you shortly.");
};

1 个答案:

答案 0 :(得分:2)

首先,您要拨打push()两次,这确实没有意义。因此,我假设您只打算调用一次。

According to the API docs push()返回一个“ ThennableReference”,这实际上只是说它返回了一个在操作完成后解决的承诺。使用此promise可以执行其他一些回调函数,以在写入完成后执行所需的操作:

inquiry.push({ ... }).then(() => {
    alert(...)
})