0

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

oussama kamal
  • 1,027
  • 2
  • 20
  • 44
  • `checkStopsInRoute` should call `callback` from **inside** the last `handle_database` callback. This is markedly easier with promises, but in your case a counter will do it. – T.J. Crowder Oct 01 '16 at 08:42
  • I am trying to collect all codes that exist so making the callback inside the handle_database will send each code at a time, am I correct? – oussama kamal Oct 01 '16 at 08:55
  • No. Read the comment again: *"...from the **last** `handle_database` callback...a counter wll do it..."* – T.J. Crowder Oct 01 '16 at 09:09
  • Sorry I don't see how, could you suggest a code to add please? – oussama kamal Oct 01 '16 at 09:15

0 Answers0