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.