Array is not updated

2

I am 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 within the query queryUsuarios if you print the values.

    
asked by sioesi 29.03.2018 в 05:31
source

1 answer

1

This problem is quite common, and it is because of the asynchrony, what is happening to you basically is that at the moment of the execution that arrives at the for that your devicesTokenNotification goes through this variable still has nothing pushed, this is because the queries to the base are slower than the execution of javascript, in addition to that the execution does not wait for the for terminate.

Here you can see ways to avoid it: link

What you should do is wait for that for.

Greetings!

    
answered by 29.03.2018 / 18:14
source