synchronous programming in nodejs, problems with asynchrony

I call from app.js asi:

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 clutter functions!!! how do I fix it? I want the Allow function to run first and then insert

 3
Author: hubman, 2016-10-04

2 answers

The problem is:

callback(booleano,usuarioNombre,usuarioPass,array);

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

What you need to do is move that statement inside the callback of your query. Such that, after doing your process, insertarLetra is called:

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);
});
 4
Author: gugadev, 2016-10-05 00:24:35

Solve it like this:

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

I don't know if it will be the best way.

 3
Author: hubman, 2016-10-05 00:33:32