I\'m using the following asynchronous function to write data to my firebase instance:
function writeUserData(uid, fn, ln, userEmail) {
firebase.database().
According to firebase docs:
https://firebase.google.com/docs/database/web/read-and-write#receive_a_promise, the set method returns a promise. In that case, the simplest example for you would be:
function writeUserData(uid, fn, ln, userEmail) {
firebase.database().ref('users/' + uid).set({
firstName: fn,
lastName: ln,
email: userEmail
}).then(function onSuccess(res) {
window.location.href = "./mypage.html";
}).catch(function onError(err) {
// do sth, e.g. console.error(err);
});
};
The difference between your code and my example is the parts I've added:
.then(function onSuccess(res) {
window.location.href = "./mypage.html";
}).catch(function onError(err) {
// do sth
});
which in short means, "if request was successful, do onSuccess. If not - do onError.
You can get more info about how Promises work here: Promise mdn docs
To improve readability you could write it this way:
function writeUserData(uid, fn, ln, userEmail) {
firebase.database().ref('users/' + uid).set({
firstName: fn,
lastName: ln,
email: userEmail
})
.then(onSuccess)
.catch(onError);
};
function onSuccess(res) {
window.location.href = "./mypage.html";
}
function onError(err) {
// do sth
}