首页 > 解决方案 > 即使成功尝试,也无法在 Firebase 上写入数据

问题描述

我试图在我的网络的数据库上写一些数据,但即使在显示成功发布数据的警报之后,数据也没有上传到 firebase。在我尝试添加将图像上传到 Firebase 存储的功能之前,它工作正常。该代码无法正常工作,因此我将其删除,但此后我无法将数据写入firebase。下面是我的代码,请看一下。

Javascript代码:-

const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customText = document.getElementById("custom-text");

customBtn.addEventListener("click", function () {
    realFileBtn.click();
});
realFileBtn.addEventListener("click", function()
{
    if (realFileBtn.value) {
        customText.innerHTML = realFileBtn.value;
    }else{
        customText.innerHTML = "No file chosen, yet.";
    }
});

$("#createBtn").click(
    function(){

        var databaseRef = firebase.database().ref('posts/');
        alert(databaseRef);

        var Title = $("#tit").val();
        var desc =  $("#dees").val();



        if (Title !="" && desc != "") {
            var uid =  firebase.database().ref().child('posts').push().key;
            alert(uid);
            var data = {
                Title: Title,
                desc: desc,
                push: uid

            };
            var updates = {};
            updates['/posts/' + uid] = data;
            alert(updates);
            firebase.database().ref().update(updates);

            alert("You blog posted successfully!");  

            window.location.reload(); 
        }else{
            alert("All fields are necessary!"); 
        }




    }
    );

请看一看。

显示 databaseRef 的警报,显示 uid 的警报,显示成功发布的数据的警报,但数据仍未存储在 firebase 实时数据库中。

标签: javascriptfirebasefirebase-realtime-database

解决方案


问题是您在调用时忘记添加回调函数update()。让我们仔细看看这两行代码:

firebase.database().ref().update(updates);
alert("You blog posted successfully!");

很容易认为,如果update()函数调用返回,则表明更新成功完成。但事实并非如此。为了让 Firebase Javascript API 与 Firebase 数据库进行通信,它需要提交一个 HTTP 请求,并且在 JavaScript 中只能异步完成。

在 Firebase API文档中,函数签名是然后继续状态返回 firebase.Promise 包含 voidupdate()update(values, onComplete)

update()这意味着在更新实际发生之前调用返回。要在更新实际发生时采取行动,您需要为onComplete参数提供回调函数,或者使用Promise API,即update().

使用 Promise API 的示例

firebase.database().ref().update(updates).then(function() {
    alert("You blog posted successfully!");
}, function(error) {
    alert("Oops, something went wrong!" + error);
});

推荐阅读