synchronous programming in nodejs, problems with asynchrony

3

I call from app.js like this:

bd.permitir(req.body.nom,req.body.pass,resultado,bd.insertarLetra);

my functions with callback are these:

var permitir=function (usuarioNombre,usuarioPass,array,callback){
    var objBD = BD();
    var booleano=1;
    console.log("oooooooooo");
    Object.keys(array).forEach(key => {
    let tiempos  = array[key];
    objBD.query('SELECT nombre from usuario', function(err, rows, fields) {
        for (var i = 0; i < rows.length; i++) {
            if(rows[i].nombre==usuarioNombre){
                booleano=0;
            }   
        };
    });
    });
    callback(booleano,usuarioNombre,usuarioPass,array);
};

var insertarLetra=function(booleano,usuarioNombre,usuarioPass,array){
    var objBD = BD();
 //insertar usuario mas los datos de las variables

    if(booleano==1){
            var post  = {NOMBRE:usuarioNombre,  PASS:usuarioPass};
            var query = objBD.query('INSERT INTO  usuario SET ?', post, function(err, result) {
                console.log(booleano);
                Object.keys(array).forEach(key => {
                    let tiempos  = array[key];
                    var post  = {ID_U:result.insertId,  LETRA:key};
                    var query = objBD.query('INSERT INTO  LETRA SET ?', post, function(err, result) {
                        for (var i = 0; i < tiempos.length; i++) {
                            var post  = {ID_L:result.insertId,  TIEMPO:tiempos[i]};
                            var query = objBD.query('INSERT INTO  TIEMPOS SET ?', post, function(err, result) {
                            });
                        };
            });
        });
            }); 
    };


    // console.log(query.sql); // INSERT INTO posts SET 'id' = 1, 'title' = 'Hello MySQL'
};

runs in disorder the functions !!! how do I solve it? I want the allow function to be executed first and then insertLetra

    
asked by hubman 04.10.2016 в 21:23
source

2 answers

3

Solve it this way:

setTimeout(function(){
    callback(booleano,usuarioNombre,usuarioPass,array);
},3000);

I do not know if it would be the best way.

    
answered by 05.10.2016 / 02:33
source
4

The problem is:

callback(booleano,usuarioNombre,usuarioPass,array);

That line, which is an execution of the function insertarLetra , is executed in the same period of time as the query.

What you should do is move that instruction inside the callback of your query. In such a way that, after doing its process, it is called insertarLetra :

objBD.query('SELECT nombre from usuario', function(err, rows, fields) {
  for (var i = 0; i < rows.length; i++) {
    if(rows[i].nombre==usuarioNombre){
      booleano=0;
    }   
  }
  // aquí llamas al callback insertarLetra
  callback(booleano,usuarioNombre,usuarioPass,array);
});
    
answered by 05.10.2016 в 02:24