Loop with a pool.query pg(postgres) in the Ode, is giving conflict in the delivery of the Sponses

Asked

Viewed 81 times

1

I’m a beginner in Node programming, I hope someone can help me, The problem is this, I am making an app with Node in which you have a for loop with the request body (req.body) and at each iteration I make a query in the postgres database with the pg library pool.query, then I put it all in an array and send it in Sponse(res). Only when I test in the browser for a request it works normally, but when I open two tabs and make two requests simultaneously, it mixes the data of the Sponses and gets the data in the wrong Sponse.
I don’t know where the bug is, follow a part of the code:

async enviaResposta(req, res){

const objResultadoFinal = [];
const body = JSON.parse(JSON.stringify(req.body));



//extrai os dados e faz a consulta no banco
 async function ExtraiEformataDados(){


    for(prop in body){

        const conteudo = body[prop];
        let select = "";

        //codigo que manipula o select 
        manipula a variável select
        //fim do do código que manipula o select


        if(select != ""){

            await pool.query(select)
            .then(res => {
                 objResultadoFinal.push({ id:prop, msgRecebidanoServidor:conteudo, resultado:res.rows});

             })
            .catch(err => {

                objResultadoFinal.push({ id: prop, msgRecebidanoServidor:conteudo, resultado:[err.stack]});



        }); 
        }else{
            objResultadoFinal.push({ id: prop, msgRecebidanoServidor:conteudo, resultado:[]}); 
        }


    }   

}

async function enviaDados(){

    await ExtraiEformataDados();

    return await res.status(200).json({
    message: "dados enviados com sucesso",
    data: objResultadoFinal
});
}

 enviaDados(); 

}

  • Reginaldo, how do you manage your server sessions? Are you aware that in Nodejs, unlike PHP and ASP, you have to write your own Session manager? If you don’t know what I’m talking about: express-session.

  • @Augusto Vasques, thanks for the tip I didn’t have much sense of sessions, I read the link, but I found out where the problem was, it was simple: no loop for in I put (prop in body), but actually it was (Let prop in body)It caused me the big problem that I spent days trying to find the mistake. But at least I learned a new subject with your help. Stay with God!!!

No answers

Browser other questions tagged

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