Firebase更新回调以检测错误并成功



如何使此回调工作?我看了文件,但不知什么原因,我就是想不通?

   var ref = new Firebase("https://xxx.firebaseio.com/public/"+$scope.uid+"/shows/");
var blast = ref.child(show_title);
blast.update({
"show_title": show_title,
"show_image": show_image,
"show_description": show_description,
"show_email": show_email,
"time": Firebase.ServerValue.TIMESTAMP
});
 blast.update("I'm writing data", function(error) {
   if (error) {
    alert("Data could not be saved." + error);
  } else {
    alert("Data saved successfully.");
  }
});

Frank的解决方案非常适合您的问题。另一种选择是使用更新承诺。如果您同时执行一系列操作,这将特别有用,在Firebase中经常出现这种情况。

这里有一个使用promise的示例

blast.update({ update: "I'm writing data" }).then(function(){
  alert("Data saved successfully.");
}).catch(function(error) {
  alert("Data could not be saved." + error);
});

您对update()的第二次调用在JavaScript控制台中引发此错误:

未捕获错误:Firebase.update失败:第一个参数必须是包含要替换的子对象的对象。(…)

update的第一个参数必须是一个对象,因此:

blast.update({ update: "I'm writing data" }, function(error) {
  if (error) {
    alert("Data could not be saved." + error);
  } else {
    alert("Data saved successfully.");
  }
});

供参考,这是update()函数的文档。

在React ES6:中

var refTypes = db.ref("products").child(productId);
var updates = {};
updates[productId] = newProduct;
refTypes.update(updates).then(()=>{
  console.log("Data saved successfully.");
}).catch((error)=> {
  console.log("Data could not be saved." + error);
});

最新更新