0

I want to execute a function CheckAndCreate() with a firebase function and execute a second function SendMessage() only when CheckAndCreate() has returned a key for a user ...

var checkAndCreate = (sessionId, fbid, prenom, nom, genre) => {
    var userz = firebase.database().ref().child("accounts").orderByChild("fbid").equalTo(fbid).once("value").then(function(snapshot) {
        var exists = (snapshot.val() !== null);
        if (exists) {
            for (var key in snapshot.val()) break;
            console.log("ouiii jexiste" + key);
            sessions[sessionId].key = key;
            // I have the key we can continue
            snapshot.forEach(function(childSnapshot)  {
                console.log('snapshot.dernier_message'+childSnapshot.val().dernier_message);
                sessions[sessionId].dernier_message = childSnapshot.val().dernier_message;
            });

        }
        else {
            admin.auth().createCustomToken(fbid).then(function(customToken) {
                firebase.auth().signInWithCustomToken(customToken).then(function() {
                    var user2 = firebase.auth().currentUser;
                    var keyid = firebase.database().ref().child('accounts').push();
                    sessions[sessionId].key = keyid.key;
                    // I have the key we can continue
                    sessions[sessionId].dernier_message = new Date();
                    firebase.database().ref().child('accounts').child(keyid.key).set({
                        fbid: fbid,
                        prenom: prenom,
                        nom: nom,
                        nb_agression : 0,
                        dernier_message : new Date(),
                        genre: genre,
                        date: new Date().toISOString()
                    }).catch(function(error) {
                        console.log("erreur from firebas 9");
                    });
                }).catch(function(error) {
                    console.log("erreur from firebas 10");
                });
            }).catch(function(error) {
                console.log("erreur from firebas 11");
            });
        } // fin
    }).catch(function(error) {
        console.log("erreur from firebas 8 once");
    });
};

My problem is the understanding of Promises and the translation in Javascript. Can I execute what I want and How can I do that ?
Thank you.

2
  • Is there a specific problem with the code you've shown? Commented Dec 11, 2017 at 17:45
  • not at all ! My only problem is actually, I execute the second function without user key because firebase is async. I need to wait for the user key Commented Dec 11, 2017 at 18:03

1 Answer 1

1

You must return a promise from CheckAndCreate function. Learn how promises work. They will help you a lot while working in nodejs.

I have shown below, the way your code should be structured to achieve what you want. I have also refactored some of your code, by taking advantage of chaining in promises. Which makes the code more readable.

var checkAndCreate = () => {
  return new Promise((resolve, reject) => {
    admin.auth().createCustomToken(fbid)
    .then((customToken) => firebase.auth().signInWithCustomToken(customToken))
    .then(() => {
          var user2 = firebase.auth().currentUser;
          var keyid = firebase.database().ref().child('accounts').push();
          sessions[sessionId].key = keyid.key;
          // I have the key we can continue
          sessions[sessionId].dernier_message = new Date();
          firebase.database().ref().child('accounts').child(keyid.key).set({
              fbid: fbid,
              prenom: prenom,
              nom: nom,
              nb_agression : 0,
              dernier_message : new Date(),
              genre: genre,
              date: new Date().toISOString()
          });
          resolve('some data you want to pass to SendMessage');
      })
      .catch((error) => {
          console.log("erreur from firebas 10");
          reject(error)
      });
  });
}

var SendMessage = () => {
  checkAndCreate()
  .then((result) => {
    // Send message based on result
  })
  .catch((err) => {
    // Do not send message
  });
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.