This is my code, I need to call callback only when the loop has reached its end.
function insertIntoCacheRange(userID, from, to, callback){
var dataRanges = new Array();
for(let pointer=from, index = parseInt(from) + 1800 ; index < to; pointer+=1800, index +=1800){
var count = 0;
var sqlSelect = "SELECT count(*) as count FROM sensordata WHERE sensorid = ? AND time >= ? AND time < ?";
con.query(sqlSelect, [userID, pointer, index], function(err, result){
count = JSON.parse(JSON.stringify(result))[0].count;
//console.log("pointer + " + pointer + " limit " + index + " = " +count);
dataRanges.push(count);
var sqlInsert = "INSERT INTO cache1800 (sensorid, time, count) VALUES(?,?,?)";
con.query(sqlInsert, [userID, pointer, count], function(err, result){
if(err) throw err;
});
});
}
callback(dataRanges);
}
Solved!! Finally I figure it out like this:
function insertIntoCacheRange(userID, from, to, callback){
var dataRanges = new Array();
for(let pointer=from, index = parseInt(from) + 1800 ; index < to; pointer+=1800, index +=1800){
var count = 0;
var sqlSelect = "SELECT count(*) as count FROM sensordata WHERE sensorid = ? AND time >= ? AND time < ?";
con.query(sqlSelect, [userID, pointer, index], function(err, result){
count = JSON.parse(JSON.stringify(result))[0].count;
//console.log("pointer + " + pointer + " limit " + index + " = " +count);
dataRanges.push(count);
var sqlInsert = "INSERT INTO cache1800 (sensorid, time, count) VALUES(?,?,?)";
con.query(sqlInsert, [userID, pointer, count], function(err, result){
if(err) throw err;
});
//We reached the end of the loop (JS, you and your sync behaviour are crazy)
if(dataRanges.length == 31){
callback(dataRanges);
}
});
}
}
I need to check if the array it's already 31 size. Then it's finished. Thank you very much for the idea :)