Reputation: 2853
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({
firstName: fn,
lastName: ln,
email: userEmail
});
};
Once writeUserData has finished, then I want to redirect the user to a different page:
window.location.href = "./mypage.html";
As far as I can understand, this can be done with promises but I could really use a good example to wrap my head around this.
Upvotes: 0
Views: 2679
Reputation: 314
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
}
Upvotes: 7