我正在嘗試將資料推送到 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");
uj5u.com熱心網友回復:
更新似乎是異步函式,回傳一個承諾。所以你應該妥善處理它。否則,可能會在更新完成之前呼叫“位置”。
像這樣改變它:
firebase.database().ref().update(updates).then(() => {
console.log("Saved successfully")
location.replace("nextpage.html");
}).catch(error => {console.log('Error:', error)})
如果你不想使用 Promise,請為 update 函式提供一個附加引數,該引數將用作回呼函式,即在 update 完成時呼叫:
firebase.database().ref().update(updates, function() {
console.log("Saved successfully")
location.replace("nextpage.html");
})
uj5u.com熱心網友回復:
該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");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/412214.html
標籤:
上一篇:云存盤與谷歌資料庫
