Perform two consecutive and dependent Mysql inserts with Node JS

Asked

Viewed 35 times

0

Good Morning Everyone.

I have a problem and I need your help.

My case is as follows: I have a TASK table and a DIAS_TAREFA table that has a foreign key for id_task. Therefore, after storing the data of a task, having succeeded, I must insert the data in the DIAS_TAREFA table according to the previously generated id. The problem I’m encountering concerns the "threads" that are running because the job registration function ends before the return of the day functionTarefaController.cadastrar() and with that the system hangs. I’m using async await but it’s no use.

Job registration function code

async function cadastrar(req, res){
var {descricao, id_categoria, hora_inicio, hora_fim, data_termino, id_usuario} = req.body.tarefa;

hora_inicio = hora_inicio==""?null:hora_inicio;
hora_fim = hora_fim==""?null:hora_fim;
data_termino = data_termino==""?null:data_termino;

const sql = "INSERT INTO TAREFA (DESCRICAO, ID_CATEGORIA, HORA_INICIO, HORA_FIM, DATA_TERMINO, ID_USUARIO) VALUES ?";

let values = [[descricao, id_categoria, hora_inicio, hora_fim, data_termino, id_usuario]];

conexao.query(sql, [values], async function (error, results, fields){
    if(error){
        return res.json({'erro':'Tarefa nao gravada'});
    }else{
        const retornoDias = await diasTarefaController.cadastrar(req,results.insertId);
        if(retornoDias){
            return res.json({'ok':'Tarefa gravada!'});    
        }  
    }
}).end;};

Day function codeTareaController.register():

async cadastrar(req, id_tarefa){
    const { segunda, terca, quarta, quinta, sexta, sabado, domingo} = req.body.dias;

    const sql = "INSERT INTO DIAS_TAREFA (ID_TAREFA, SEGUNDA, TERCA, QUARTA, QUINTA, SEXTA, SABADO, DOMINGO)  VALUES ?";

    const values = [[
        id_tarefa,
        segunda,
        terca,
        quarta,
        quinta,
        sexta,
        sabado,
        domingo
    ]];

    conexao.query(sql, [values], function(error, result, field){
        if(error){
            return false;
        }else{
            return true;
        }
    });
}
  • is generating some kind of explicit error? or only hangs same time of saving day_tasks?

  • No mistakes. Just hangs even.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.