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;