I'm working with NodeJS, I create a Array
and then I make a query to my database. When I get results, I do push
to add elements to the array, however when I want to print the elements there is nothing.
function sendMessageToUser(req, res) {
var devicesTokenNotification = new Array();
req.getConnection(function(err,connection){
var query = connection.query('SELECT usuario_id, PERIOD_DIFF(DATE_FORMAT(created, "%Y%m"), DATE_FORMAT(NOW(), "%Y%m")) as meses FROM documento', [], function(err, rows){
if(err)
console.log("Error Selecting : %s ",err );
if (rows.length > 0) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].meses > 7){
var queryUsuarios = connection.query('SELECT deviceToken from usuario where id = ?', [rows[i].usuario_id], function(err, row){
if(err)
console.log("Error Selecting : %s ",err );
devicesTokenNotification.push(row[0].deviceToken);
});
}
}
}
for (var cont = 0; cont < devicesTokenNotification.length; cont++) {
console.log(devicesTokenNotification[cont]);
}
});
});
};
However, if I apply the same for
but inside the query queryUsuarios
if it prints the values.
This problem is quite common, and it is due to asynchrony, what is basically happening to you is that at the moment of the execution that reaches the for that goes through your devicesTokenNotification this variable still does not have anything pushed, this is because the queries to the base are slower than the execution of javascript, in addition to the fact that the execution does not wait for the for to finish.
Here you can see ways to avoid it: https://carlosazaustre.es/manejando-la-asincronia-en-javascript/
What you should do is wait for that for to finish.
Cheers!