Do an asynchronous function wait for another

2

I'm developing a JavaScript system with Node.JS and Redis, however, because of the asynchronous functions, the loop terminates before the functions, which causes the wrong response array or the timeout on the server. In the face of my problem, is it possible to make the functions wait for each other? What would be a possible solution to my problem?

Code of what I've done so far:

var express = require('express');
var router = express.Router();
var redis = require('redis'),
    client = redis.createClient(32769, '192.168.99.100');

client.on("error", function (err) {
    console.log("Error " + err);
});

router.post('/UsuarioLogadoPossuiAcoes', function (req, res) {

    var templateKey = 'Usuario:' + req.body.token;

    var resposta = [];

    for (var i = 0; i < req.body.Acoes.length ; i++) {

        var Namespace = req.body.Acoes[i].split('.');
        var Verbo = Namespace.pop();
        Namespace = Namespace.join('.');
        var chave = templateKey + ':' + Namespace;

        client.exists(chave, function (err, existe) {

            if (existe == 1) {

                client.sscan(chave, 0, 'MATCH', Verbo, function (err, resultado) {

                    resposta[i] = (resultado[1].length > 0);
                    console.log(i + ' - ' + resposta[i]);
                    console.log(chave + '.' + Verbo);

                    //Verifica se as validações terminaram, encerra a conexão com o redis e responde a conexão
                    if (req.body.Acoes.length == resposta.length) {

                        client.end();
                        res.json(resposta);

                    }

                });

            } else {

                // Procura no banco relacional e faz o cache no redis

                resposta[i] = false;
                console.log(i + ' - ' + resposta[i]);

                //Verifica se as validações terminaram, encerra a conexão com o redis e responde a conexão
                if (req.body.Acoes.length == resposta.length) {

                    client.end();
                    res.json(resposta);

                }
            }
        });
    }    
});

module.exports = router;
    
asked by anonymous 11.01.2016 / 20:15

2 answers

0

Well, what I did to solve my problem was a recursive function with a callback and in the callback I give the answer. This is currently solving my problem.

    
18.01.2016 / 13:51
3

Ideally, everything within for should occur within a separate function, but I believe that just changing this:

for (var i = 0; i < req.body.Acoes.length ; i++) {
   //...
}

To:

req.body.Acoes.forEach(function(acao, i, Acoes) {
  //...
});

Solve your problem. The loop ends before the asynchronous functions end, but in the second case the index variable is contextualized within the body of the function, so even after the asynchronous function runs out, the value of i will remain the same.

Remembering that within the forEach function you would stop using req.body.Acoes[i] to refer to each item and would use the acao parameter (or whatever name you prefer).

Reference to forEach documentation on MDN .

    
12.01.2016 / 17:19