1

I am getting data from a MySQL query and then pushing the elements into an array. However, once I move out of the query the array is empty. I guess it is because the elements in the array are only references. But how do I keep the elements inside the array?

var timeblocked = [];
var timeunblocked = [];
connection.query("SELECT user_relationships.*, block_intervals.* FROM user_relationships INNER JOIN block_intervals ON user_relationships.id = block_intervals.relationfk WHERE (user1 = '"+currentUserID+"' AND user2 = '"+user2_in_blockedRelationship+"' AND timeunblocked IS NOT NULL)", function(error, resultsForBlock){
  for (var i = 0; i<resultsForBlock.length; i++) {
    timeblocked.push(resultsForBlock[i].timeblocked);
   timeunblocked.push(resultsForBlock[i].timeunblocked);
  }
console.log("1. timeblocked: ", timeblocked, "timeunblocked: ", timeunblocked); // shows all of the elements in the array
});
console.log("2. timeblocked: ", timeblocked, "timeunblocked: ", timeunblocked); //This shows an empty array

Why is the second console.log() NOT logging the array?

suonpera
  • 225
  • 1
  • 5
  • 13

1 Answers1

1

This is asynchronous behaviour. You should wait to execute the stuff after you completed the callback execution.

Your second console log gets executed before the call to db completed.

Best way is to use the array only after you done with sql call.

connection.query("SELECT user_relationships.*, block_intervals.* FROM user_relationships INNER JOIN block_intervals ON user_relationships.id = block_intervals.relationfk WHERE (user1 = '"+currentUserID+"' AND user2 = '"+user2_in_blockedRelationship+"' AND timeunblocked IS NOT NULL)", function(error, resultsForBlock){
  for (var i = 0; i<resultsForBlock.length; i++) {
    timeblocked.push(resultsForBlock[i].timeblocked);
      timeunblocked.push(resultsForBlock[i].timeunblocked);
  }
console.log("1. timeblocked: ", timeblocked, "timeunblocked: ", timeunblocked); // shows all of the elements in the array



// TODO -- remaining all code that uses the array.

});

Better you use promises if you are not aware.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307