Node js, promises, callback

Asked

Viewed 170 times

2

I need to run certain updates and delete within a query return in my controller. but only the last function is executed I don’t think I understand how to use promises.

 api.adMaster =  function (req, res) {
        var dados = req.body;
        var ultimo = false;
        var addados = {ad:'', emp:''}
        var time = new Date();
        var promessas = [];
        var resutados = [];

        for (var i = 0; i < dados.length ; i++) {
            if(dados[i].aut.length>2){
                var metade = Math.floor(dados[i].aut.length / 2);
                var resultado = "'"+dados[i].aut.substr(0,metade)+"','"+dados[i].aut.substr(metade)+"'";
                dados[i].aut = resultado
                dados[i].data = convertData(time);
                dados[i].hora = converHora(time);
            }
            addados.ad += ","+dados[i].ad
            addados.emp += ","+dados[i].emp
        }
        addados.ad =  addados.ad.substring(1);
        addados.emp =  addados.emp.substring(1);
        var promessas = [];
        solicitacaoSqlDAO.adMaster(addados, function (erro, recordset) {
            if (erro) {
                console.log("#$# Erro ao adMaster #$#");
                console.log(erro);
            } else {
                var compAD = '';
                var ad;
                console.log( recordset.recordset.length);
                recordset.recordset.forEach(function(data, index) {
                    ad = data;
                    if(compAD==data.NUM_AD){
                        ultimo = true;
                    }
                    if( recordset.recordset.length ==  1){
                        ultimo = true;
                    }
                    if(ultimo || !dados[0].condicao){ 
                        promessas.push(new Promise(function(resolver, rejeitar) {
                            solicitacaoSqlDAO.updateiesSupCapS(ad).then(result=>{
                                resutados.push(result);
                                console.log('updateiesSupCapS');
                                resolver();
                            }).catch(err => {
                                console.log(" @###$$$$##$  ERRO updateiesSupCapS  ###$$$#$#$#$$#");
                                console.log(err);
                                console.log(" @###$$$$##$  ERRO updateiesSupCapS  ###$$$#$#$#$$#");
                            });
                        }));
                        promessas.push(new Promise(function(resolver, rejeitar) {
                            solicitacaoSqlDAO.updateiesSupCapC(ad).then(result=>{
                                resutados.push(result);
                                console.log('updateiesSupCapC');
                                resolver();
                            }).catch(err => {
                                console.log(" @###$$$$##$  ERRO  updateiesSupCapC ###$$$#$#$#$$#");
                                console.log(err);
                                console.log(" @###$$$$##$  ERRO  updateiesSupCapC ###$$$#$#$#$$#");
                            });
                        }));
                        promessas.push(new Promise(function(resolver, rejeitar) {
                            solicitacaoSqlDAO.updateIesLibPgtoCapN(ad).then(result=>{
                                resutados.push(result);
                                console.log('updateIesLibPgtoCapN');
                                resolver();
                            }).catch(err => {
                                console.log(" @###$$$$##$  ERRO  updateIesLibPgtoCapN  ###$$$#$#$#$$#");
                                console.log(err);
                                console.log(" @###$$$$##$  ERRO  updateIesLibPgtoCapN  ###$$$#$#$#$$#");
                            });
                        }));
                        promessas.push(new Promise(function(resolver, rejeitar) {
                            solicitacaoSqlDAO.deleteCapAdSuspAprov(ad).then(result=>{
                                resutados.push(result);
                                console.log('deleteCapAdSuspAprov');
                                resolver();
                            }).catch(err => {
                                console.log(" @###$$$$##$  ERRO  deleteCapAdSuspAprov  ###$$$#$#$#$$#");
                                console.log(err);
                                console.log(" @###$$$$##$  ERRO  deleteCapAdSuspAprov  ###$$$#$#$#$$#");
                            }); 
                        }));
                        ultimo = false;
                        compAD=data.NUM_AD; 


                    }else{
                        res.status(200).json({resutado:'aguardando outro aprovador'});;
                    }
                });
                Promise.all([true, promessas]).then(function(values) {
                    console.log(values);
                    res.status(200).json(resutados);
                }).catch(function() {
                    res.status(404).json("erro");
                });
            }
        })
    };

In my console debug.log(values) comes that result

[ true,
  [ Promise { <pending> },
    Promise { <pending> },
    Promise { <pending> },
    Promise { <pending> },
    Promise { <pending> },
    Promise { <pending> },
    Promise { <pending> },
    Promise { <pending> },
    Promise { <pending> },
    Promise { <pending> },
    Promise { <pending> },
    Promise { <pending> } ] ]

1 answer

1


You’re doing well with the Promises but not with the Promise.all, this method accepts an array of Promises. What you are giving it is an array with a boolean and an array.

Use like this:

Promise.all(promessas).then(... etc...

Note also that in the end, inside Promise.all you have

res.status(200).json(resutados);

and I think you want to values:

res.status(200).json(values);
  • Sergio, just to leave the feedback, I had to perform the consultation in another way, I believe there was something about the way I implemented my DAO, I will have to stop for an hour to see this more calmly. de ja thanks ai by force.. I have actually learned ways to implement promises and mapping haha vlw

  • @Cirostodulskideazevedo hi! I’m out of the house this week, so I’ll be around a bit. I take a look after again!

Browser other questions tagged

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