I have a function that checks a list of codes if the exist in a database and save them in an array in case they exist :
function checkStopsInRoute(stops, callback) {
var already_in_route_stops = [];
for (var prop in stops) {
if (stops.hasOwnProperty(prop)) {
var code = stops[prop]["cmp_code"];
var query_check_stop = "SELECT code FROM stops WHERE code = '" + code + "' AND date = '" + todayDate('/') + "'";
handle_database(query_check_stop, true, function (response) {
if (!isEmpty(response)) {
console.log("response "+response);
already_in_route_stops.push(code);
}
});
}
}
console.log(already_in_route_stops);
callback(already_in_route_stops);
}
This function is called in my app.js like :
app.post('/add_companies_to_route', function (req, res) {
var stops = req.body;
checkStopsInRoute(stops, function(response){
if (!isEmpty(response)) {
res.send(prepareResponse("KO", "The stops with the following codes (" + response + ") are already in the route for the current day! Please remove them from the selection", "Error", false));
}else{
}
});
});
Sounds like the for loop in "checkStopsInRoute" function does not wait until the stops are checked and the array "already_in_route_stops" filled because I get in the console:
[]
response [object Object]
response [object Object]
response [object Object]
Any help please?
Thanks