I'm programming in javascript (I'm new) and I've noticed that sometimes it does not run sequentially, I've seen that it's because it runs asynchronously.
So far I have half escaped with the setTimeout function, but I would like to know if there are other ways to control the execution of javascript to do exactly what I want.
In my particular case, I have this code where I access firebase to get the number of children of a node:
firebase.initializeApp(config);
var database = firebase.database();
var numerojaja;
// TO-DO : obtener el numero de peliculas
firebase.database().ref('/peliculas/').once('value').then(function(snapshot) {
numerojaja=snapshot.numChildren();
console.log(numerojaja);
});
console.log(numerojaja);
// **********
var numero_p=3; // de momento
var nombre_p="hhola";
var descripcion="esto es una descripcion";
var reputacion="y esto una reputacion";
var cartelera="esto es una direccion de una imagen";
// for(etc.......){
document.write('<tr>');
document.write('<th scope="row">'+nombre_p+'</th>');
document.write('<td>'+descripcion+' </td>');
document.write('<td>'+reputacion+'</td>');
document.write('<td><img src="'+direccion+'" class=".img-responsive" alt="Cinque Terre " style="max-width: 20%;"> </td>');
document.write('</tr>');
// end for.......
The problem is within the following code section:
var numerojaja;
// TO-DO : obtener el numero de peliculas
firebase.database().ref('/peliculas/').once('value').then(function(snapshot) {
numerojaja=snapshot.numChildren();
console.log(numerojaja);
});
Javascript decides first to skip the execution within the function and continues, and once it has finished executing the rest, executes the function. Making that when I want to access said value I can not because it has not been executed yet.
Thank you very much.