javascript - 即使成功尝试,也无法在 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 实时数据库中。
解决方案
问题是您在调用时忘记添加回调函数update()
。让我们仔细看看这两行代码:
firebase.database().ref().update(updates);
alert("You blog posted successfully!");
很容易认为,如果update()
函数调用返回,则表明更新成功完成。但事实并非如此。为了让 Firebase Javascript API 与 Firebase 数据库进行通信,它需要提交一个 HTTP 请求,并且在 JavaScript 中只能异步完成。
在 Firebase API文档中,函数签名是然后继续状态返回 firebase.Promise 包含 void。update()
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);
});
推荐阅读
- android - facebook graph api 使应用程序自动抓取 url android
- amazon-web-services - AWS SAM 模板 - 本地测试
- safari - 如何在 Safari 12.0.1 中获取 indexedDB 存储配额?
- python - 烧瓶设置饼干
- javascript - 读取源 html 以进行匹配然后使用 google 搜索的小书签
- c# - 使用 Visual Studio 2017 调试简单的 ASP.NET Core 2.1.5 模板
- c# - 无法获取 json 对象数据
- java - Java - 在 Try/Catch 期间弹出随机“null”
- angularjs - AngularJS - 使用 ng-include 将相同的范围绑定到表单的多个副本
- java - 用 Java 中的属性文件中的值替换 HashMap 键