在数组中推送元素后,它是空的

时间:2017-08-17 09:44:59

标签: javascript mysql arrays

我从MySQL查询中获取数据,然后将元素推送到数组中。但是,一旦我离开查询,数组就是空的。我想这是因为数组中的元素只是引用。但是如何将元素保留在数组中呢?



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
&#13;
&#13;
&#13;

为什么第二个console.log() NOT 记录数组?

1 个答案:

答案 0 :(得分:1)

这是异步行为。完成回调执行后,您应该等待执行这些操作。

第二个控制台日志在db完成调用之前执行。

最好的方法是在完成sql调用后才使用该数组。

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.

});

如果您不知道,最好使用promises