I am working on a web app, and I am facing a problem. I have simplified the question. I am declaring an array globally i.e. outside of the loop. when I push data into it and then I output that array on the end of the loop and outside the loop it return empty array, why is that . Even when I output the data inside the loop it returns the push data, but outside of the loop it returns the empty array as declared, means no data has been pushed to it.
var last_data = [],
last_time, last_text;
for (var i = 0; i < res.length; i++) {
var GET_LASTMESS_AND_TIME = "SELECT username,mess_txt,mess_time FROM (select mess_to as user_id,mess_txt,mess_time from messages where mess_from = '" + res[i].id + "' AND mess_to='" + data + "' UNION select mess_to as user_id,mess_txt,mess_time from messages where mess_from = '" + data + "' AND mess_to='" + res[i].id + "') sq join users on users.id = sq.user_id";
con.query(GET_LASTMESS_AND_TIME, (e, r) => {
if (e) throw e;
var len = r.length;
last_time = r[len - 1].mess_time;
last_text = r[len - 1].mess_txt;
last_data.push({
date: last_time,
text: last_text
});
socket.emit("user_messages_list", {
result: res,
last_data: last_data
});
});
}
console.log(last_data);
When I tried the below sample example, it returns the data which has been pushed to it.
var data = [],
a, b;
for (var i = 0; i < 10; i++) {
a = i + 10;
b = i + 20;
data.push({
val1: a,
val2: b
});
}
console.log(data);