NodeJS异步问题

时间:2016-10-01 08:37:17

标签: javascript node.js

我有一个函数,如果存在于数据库中,则检查代码列表,并将它们保存在数组中,以防它们存在:

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);
}

在我的app.js中调用此函数,如:

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{

            }
        });
});

听起来像" checkStopsInRoute"中的for循环函数不会等到检查停止并且数组" already_in_route_stops"因为我进入控制台而被填满了:

[]
response [object Object]
response [object Object]
response [object Object]

请帮忙吗?

由于

0 个答案:

没有答案