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({
    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.

Answers:

Answer

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
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.