How to wait for firebase.database().ref('users/' + userId).set() to finish before calling next function?

前端 未结 1 1832
执念已碎
执念已碎 2021-01-07 12:59

I\'m using the following asynchronous function to write data to my firebase instance:

function writeUserData(uid, fn, ln, userEmail) {
  firebase.database().         


        
相关标签:
1条回答
  • 2021-01-07 13:31

    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
    }
    
    0 讨论(0)
提交回复
热议问题