添加 "location.replace" 时 Firebase 实时数据库不保存数据

Firebase Realtime Database not saving data when I add "location.replace"

我正在尝试将数据推送到 Firebase 实时数据库,在推送(并保存)数据后,浏览器应该会打开另一个页面。我使用“location.replace()”函数打开下一页但是添加 location.replace 行使数据不保存在 Firebase 实时数据库中.

这是我的代码

var updates = {};
updates['/users/' + document.getElementById('username').value] = data;
firebase.database().ref().update(updates);
console.log("Saved successfully")
location.replace("nextpage.html");

update函数是异步的;需要一些时间才能完成。如果您想等到更新完成,那么您将需要使用 promise it returns:

var updates = {};
updates['/users/' + document.getElementById('username').value] = data;
firebase.database().ref().update(updates)
  .then(() => {
    console.log('Saved successfully');
    location.replace('nextpage.html');
  });

async/await:

async function someFunction () {
  var updates = {};
  updates['/users/' + document.getElementById('username').value] = data;
  await firebase.database().ref().update(updates);
  console.log("Saved successfully")
  location.replace("nextpage.html");
}

更新似乎是异步函数,返回一个承诺。 所以你应该妥善处理它。否则可能会在更新完成之前调用“位置”。

改成这样:

firebase.database().ref().update(updates).then(() => {
  console.log("Saved successfully")
  location.replace("nextpage.html");
}).catch(error => {console.log('Error:', error)})

如果您不想使用 promise,请为更新函数提供一个额外的参数作为回调函数,即在更新完成时调用:

firebase.database().ref().update(updates, function() {
  console.log("Saved successfully")
  location.replace("nextpage.html");
})