【问题标题】:Firebase Realtime Database not saving data when I add "location.replace"当我添加“location.replace”时,Firebase 实时数据库不保存数据
【发布时间】:2026-01-23 02:45:02
【问题描述】:

我正在尝试将数据推送到 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");

【问题讨论】:

    标签: javascript html firebase firebase-realtime-database google-cloud-firestore


    【解决方案1】:

    update 函数是异步的;这需要一些时间才能完成。如果你想等到更新完成,那么你需要使用它返回的承诺:

    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");
    }
    

    【讨论】:

      【解决方案2】:

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

      改成这样:

      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");
      })
       
      

      【讨论】:

        最近更新 更多