简体   繁体   English

Javascript承诺和Firebase

[英]Javascript Promises and Firebase

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 ... 我想执行带有Firebase函数的功能CheckAndCreate()并仅在CheckAndCreate()为用户返回密钥时才执行第二个函数SendMessage() ...

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. 我的问题是对Promises的理解以及Javascript中的翻译。 Can I execute what I want and How can I do that ? 我可以执行我想要的吗,我该怎么做?
Thank you. 谢谢。

You must return a promise from CheckAndCreate function. 您必须从CheckAndCreate函数返回一个CheckAndCreate Learn how promises work. 了解诺言如何运作。 They will help you a lot while working in nodejs. 在使用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
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM