【问题标题】:How to implement promise in firebase realtime database?如何在firebase实时数据库中实现promise?
【发布时间】:2021-02-05 05:37:32
【问题描述】:

我编写了从 firebase 实时数据库中检索数据的 JavaScript,并且运行良好。我还在每个快照上提供了一个 html 表单。但是当我尝试提交表单时,它显示错误:无法读取 null 的属性“addEventListener”。这可能是因为,从 firebase 检索数据需要一些时间,但平均而言,它下面的 javascript 运行的时间,因此它找不到提交按钮。我还想从快照中为表单附加一些值。

// Initialize Firebase
var config = {
  //my config
};
firebase.initializeApp(config);

var database = firebase.database();
var ref = database.ref("Listings/" + "/electrician");

ref.on("value", function (snapshot) {
  snapshot.forEach(function (childSnapshot) {
  
  });
  var database = firebase.database();
  database.ref("Listings/" + "/electrician").once("value", function (snapshot) {
    if (snapshot.exists()) {
      var content = "";
      content += '<div class="row row-cols-1 row-cols-md-2">'; //Works one time not for each
      snapshot.forEach(function (data) {
        var val = data.val();
        content +=
          "<div class=" +
          "column" +
          " " +
          "data-string=" +
          val.ServiceArea +
          "," +
          val.onlinePayment +
          "," +
          val.DoorstepService +
          "," +
          val.address +
          "," +
          val.business +
          "," +
          ">";
        content += '<div class="card">';
        content += '<div class="card-body">';
        content +=
          '<img src="https://img.icons8.com/color/200/000000/user-male-circle.png" height="64px" height="64px" align="left" class="algn"/>';
        content += '<p class="card-text">';
        content +=
          "<b>" +
          "<font size=" +
          "4.5" +
          ">" +
          val.business +
          "</font>" +
          "</b>" +
          "<br>";
        content +=
          '<img src="https://img.icons8.com/color/500/000000/marker.png" height="20px" width="20px"/>';
        content += val.address + "<br><br></br>";
        content +=
          '<img src="https://img.icons8.com/flat_round/200/000000/star.png" height="20px" width="20px"/>100% positive response<br>';
        content +=
          "<img src=" +
          val.verification +
          " " +
          "height=" +
          "20px" +
          " " +
          "width=" +
          "20px" +
          " " +
          "/>" +
          "ID Verified";
        content += "<hr>";
        content += '<div class="description">';
        content += "<b>Business Hours:</b>&nbsp;" + val.BusinessHours + "<br>";
        content += "<b>Service Radius:</b>&nbsp;" + val.ServiceArea + "<br>";
        content += "<b>Payment Mode:</b>&nbsp;" + val.onlinePayment + "<br>";
        content +=
          "<b>Doorstep service:</b>&nbsp;" + val.DoorstepService + "<br>";
        content += "<b>Services:</b>&nbsp;" + val.services + "<br>";
        content += "</div>";
        content += "</p>";
        content += '<ul style="display: inline-block";>';
        content +=
          "<a href=tel:" +
          val.phone +
          ">" +
          "<li><button class='btn btn-primary'>Call now</button></li></a>";
        content +=
          "<a href=https://wa.me/91" +
          val.phone +
          ">" +
          "<li><button class='btn btn-success'>WhatsApp</button></li></a>";
        content += "</ul>";
        /*   content +=   */
        content += '<div class="alert" id="greeting"></div>';
        content += '<form id="contactForm">';
        content +=
          '<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" required/>';
        content +=
          '<input type="text" class="form-control" name="email" id="email" placeholder="Your Email" required />';
        content +=
          '<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" />';
        content +=
          '<input type="text" class="form-control" name="date" id="date" placeholder="Enter todays date" />';
        content +=
          '<textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea>';
        content +=
          '<button type="submit" class="btn btn-primary" style="line-height: initial;">Submit</button>';
        content += "</form>";
        content += "</div>";
        content += "</div>";
        content += "</div>";
      });
      $("#ex-table").append(content);
    }
  });
});
// reference testme collection
var testmeRef = firebase.database().ref("testme");

/* Event Listener */

document.getElementById("contactForm").addEventListener("submit", submitForm);

// Submit form
function submitForm(e) {
  e.preventDefault();

  var name = getInputVal("name");
  var email = getInputVal("email");
  var subject = getInputVal("subject");
  var date = getInputVal("date");
  var message = getInputVal("message");

  // save testme
  savetestme(name, email, subject, date, message);

  // show alert
  document.querySelector(".alert").style.display = "block";
  var testme = document.querySelector("#greeting");
  window.location.href = "SuccessfulMessage.html";

  // Hide alert after 3 seconds
  setTimeout(function () {
    document.querySelector(".alert").style.display = "none";
  }, 3000);
  // Clear form after submission
  document.getElementById("contactForm").reset();
}

/* Function to get form values */
function getInputVal(id) {
  return document.getElementById(id).value;
}

// Save testme to firebase

function savetestme(name, email, subject, date, message) {
  var newtestmeRef = testmeRef.push();
  newtestmeRef.set({
    name: name,
    email: email,
    subject: subject,
    date: date,
    message: message,
  });
}
 &lt;div id="ex-table"&gt;&lt;/div&gt;

因此,我试图提供 Promise 功能,但我无法做到。或者如果有其他方法请提及。

Retrieved data & the form

【问题讨论】:

    标签: javascript firebase firebase-realtime-database


    【解决方案1】:
    // Initialize Firebase
    var config = {
      //my config
    };
    firebase.initializeApp(config);
    
    var database = firebase.database();
    var ref = database.ref("Listings/" + "/electrician");
    
    var myPromise = new Promise(function (myResolve, myReject) {
      ref.on("value", function (snapshot) {
        snapshot.forEach(function (childSnapshot) {});
        ref.once("value", function (snapshot) {
          if (snapshot.exists()) {
            var content = "";
            content += '<div class="row row-cols-1 row-cols-md-2">'; //Works one time not for each
            snapshot.forEach(function (data) {
              var val = data.val();
              content +=
                "<div class=" +
                "column" +
                " " +
                "data-string=" +
                val.ServiceArea +
                "," +
                val.onlinePayment +
                "," +
                val.DoorstepService +
                "," +
                val.address +
                "," +
                val.business +
                "," +
                ">";
              content += '<div class="card">';
              content += '<div class="card-body">';
              content +=
                '<img src="https://img.icons8.com/color/200/000000/user-male-circle.png" height="64px" height="64px" align="left" class="algn"/>';
              content += '<p class="card-text">';
              content +=
                "<b>" +
                "<font size=" +
                "4.5" +
                ">" +
                val.business +
                "</font>" +
                "</b>" +
                "<br>";
              content +=
                '<img src="https://img.icons8.com/color/500/000000/marker.png" height="20px" width="20px"/>';
              content += val.address + "<br><br></br>";
              content +=
                '<img src="https://img.icons8.com/flat_round/200/000000/star.png" height="20px" width="20px"/>100% positive response<br>';
              content +=
                "<img src=" +
                val.verification +
                " " +
                "height=" +
                "20px" +
                " " +
                "width=" +
                "20px" +
                " " +
                "/>" +
                "ID Verified";
              content += "<hr>";
              content += '<div class="description">';
              content +=
                "<b>Business Hours:</b>&nbsp;" + val.BusinessHours + "<br>";
              content += "<b>Service Radius:</b>&nbsp;" + val.ServiceArea + "<br>";
              content += "<b>Payment Mode:</b>&nbsp;" + val.onlinePayment + "<br>";
              content +=
                "<b>Doorstep service:</b>&nbsp;" + val.DoorstepService + "<br>";
              content += "<b>Services:</b>&nbsp;" + val.services + "<br>";
              content += "</div>";
              content += "</p>";
              content += '<ul style="display: inline-block";>';
              content +=
                "<a href=tel:" +
                val.phone +
                ">" +
                "<li><button class='btn btn-primary'>Call now</button></li></a>";
              content +=
                "<a href=https://wa.me/91" +
                val.phone +
                ">" +
                "<li><button class='btn btn-success'>WhatsApp</button></li></a>";
              content += "</ul>";
              /*   content +=   */
              content += '<div class="alert" id="greeting"></div>';
              content += '<form id="contactForm">';
              content +=
                '<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" required/>';
              content +=
                '<input type="text" class="form-control" name="email" id="email" placeholder="Your Email" required />';
              content +=
                '<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" />';
              content +=
                '<input type="text" class="form-control" name="date" id="date" placeholder="Enter todays date" />';
              content +=
                '<textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea>';
              content +=
                '<button type="submit" class="btn btn-primary" style="line-height: initial;">Submit</button>';
              content += "</form>";
              content += "</div>";
              content += "</div>";
              content += "</div>";
            });
            $("#ex-table").append(content);
            myResolve();
          }
        });
      });
    });
    
    myPromise.then(function () {
      // reference testme collection
      var testmeRef = firebase.database().ref("testme");
    
      /* Event Listener */
    
      document.getElementById("contactForm").addEventListener("submit", submitForm);
    
      // Submit form
      function submitForm(e) {
        e.preventDefault();
    
        var name = getInputVal("name");
        var email = getInputVal("email");
        var subject = getInputVal("subject");
        var date = getInputVal("date");
        var message = getInputVal("message");
    
        // save testme
        savetestme(name, email, subject, date, message);
    
        // show alert
        document.querySelector(".alert").style.display = "block";
        var testme = document.querySelector("#greeting");
        window.location.href = "SuccessfulMessage.html";
    
        // Hide alert after 3 seconds
        setTimeout(function () {
          document.querySelector(".alert").style.display = "none";
        }, 3000);
        // Clear form after submission
        document.getElementById("contactForm").reset();
      }
    
      /* Function to get form values */
      function getInputVal(id) {
        return document.getElementById(id).value;
      }
    
      // Save testme to firebase
    
      function savetestme(name, email, subject, date, message) {
        var newtestmeRef = testmeRef.push();
        newtestmeRef.set({
          name: name,
          email: email,
          subject: subject,
          date: date,
          message: message,
        });
      }
    });
    

    【讨论】:

    • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
    猜你喜欢
    • 2016-11-28
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 2017-04-04
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    相关资源
    最近更新 更多