how to control the execution of javascript

1

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.

    
asked by k1k4ss0 01.01.2019 в 14:23
source

1 answer

2

Ok buddy, the problem is that, because you want to manipulate the data of your snapshot outside the event ? A more database has a method with a callback function ( then() ) to execute your code immediately and consecutively to obtain the data. JavaScript itself is an asynchronous language, so it's the expected behavior, watch this .

Naturally if you want to do something in a function, you have to finish doing it within the function, unless you make it return a specific value and call it when executing the code.

See the following examples:

var str;

setTimeout(function(){
  str = "hola"
},2000);

console.log(str);

JavaScript will never wait for two seconds to pass before you can print the variable while it is outside the function, for that is the function itself to change the value of more if it were not so it would be impossible to load a web page. .. then why is it necessary to print it out if I can do it inside? is the right question.

Remember that a function is not the same as a conditional ... let's see the following code:

var str;

if (str == undefined){
  str = "hola"
}

console.log(str);

This works because the conditional evaluates sequentially the data that are being compared and changes or executes depending on it, so this time it will not be undefined .

Now, if you have a function that you invoke when executing the code in real time, this time if you are going to return the desired result:

var str;

    function hola(str){
      str = "hola"
      return str
    }

    console.log(hola(str));

Then, the conclusion:

If you need to execute code that has to do with the function within the function itself, do it inside and the result will be synchronized.

As it should be:

var str;

    setTimeout(function(){
      str = "hola"
      console.log(str);
    },2000);

As an additional value I recommend that you read the documentation of the tools you use, for example:

  

When you receive your snapshot in your code, you put :    "numerojaja=snapshot.numChildren();"

This will be equal to undefined because the snapshot is an object from which you need to collect its value using the val() method of database (or JQuery), the correct way would be:

var data = snapshot.val();
var numerojaja = data.numChildren; //Sin () a de mas ya que no es una funcion, es un objeto.

Then the correct form would be, executing your code inside the function of the event or within the function of then() :

db.ref('/peliculas').once('value', function(snapshot) {  
   var data =snapshot.val();
   var numerojaja = data.numChildren;
   console.log(numerojaja);
 }).then(function(){
   console.log(numerojaja)           
 });

Here I leave you Read and write data on the Web and Detect value events .

I hope it's helpful, Greetings!

    
answered by 01.01.2019 / 15:50
source