How To Wait For Firebase.database().ref('users/' + UserId).set() To Finish Before Calling Next Function?
I'm using the following asynchronous function to write data to my firebase instance: function writeUserData(uid, fn, ln, userEmail) { firebase.database().ref('users/' + uid).set(
Solution 1:
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
}
Post a Comment for "How To Wait For Firebase.database().ref('users/' + UserId).set() To Finish Before Calling Next Function?"