Nodejs嵌套的ForEach回调接收空结果

时间:2019-07-19 06:05:07

标签: javascript node.js

当我尝试在foreach内进行console.log时,我正在尝试使用此函数创建时间表,它可以正确响应并打印,但是当我尝试将数据作为回调参数发送时,该函数向我显示空结果

    GetTimeTable(callback) {
    get_days = "SELECT * FROM days";
    var DayResponses = "";
    var TimeResponse = "";
    var day = 0;
    var time = 0;
    var table = "";
    var itemsProcessed = 0;
    connection.query(con, 'SELECT * FROM days', function (response_day) {
        response_day.forEach(Day => {
            DayResponses = Day;
            connection.query(con, 'SELECT * FROM time', function (response_time) {
                response_time.forEach(Time => {
                    TimeResponse = Time;
                    connection.query(con, 'SELECT * FROM time_table', function (response_time_table) {
                        response_time_table.forEach(time_table => {
                            table += DayResponses
                        })
                    }, 'SELECT')//Time   
                })
            }, 'SELECT')//Time
            itemsProcessed++;

            if (itemsProcessed == response_day.length) {

                callback(table);
            }

        });//Fore Day

    }, 'SELECT')//Days  
}

}

self.GetTimeTable(function (respones) {
console.log(respones)//Emty reuslt

});

1 个答案:

答案 0 :(得分:0)

是的,我知道这有点晚了,但是如果有人遇到这种问题,那么我会给出解决方案

GetTimeTabe(){
    new Promise((resolve,reject)=>{
        connection.query(con, 'SELECT * FROM days', function (response_day) {
            if(response_day.length != null){//in here if the query whent wrong it's responding with a null and if there is no data it will send a empty array 
                resolve(response_day)
            }else{
                reject(response_day);
            }
        })
    }).then((data)=>{
        new Promise((resolve,reject)=>{
            connection.query(con, 'SELECT * FROM time', function (response_time) {
                if(response_time.length != null){//in here if the query whent wrong it's responding with a null and if there is no data it will send a empty array 
                    resolve(response_time)
                }else{
                    reject(response_time);
                }
            })
        }).then((data)=>{
            new Promise((resolve,rejct)=>{
                data.forEach(Time => {
                    TimeResponse = Time;
                    connection.query(con, 'SELECT * FROM time_table', function (response_time_table) {
                        response_time_table.forEach(time_table => {
                            table += DayResponses
                        })
                    }, 'SELECT')//Time    
                    itemsProcessed++; 
            })
            if (itemsProcessed == response_day.length) {
    
                callback(table);
            }
            })
    })
    })
}

这是有点旧的代码,所以这是我使用的Promise的第一个代码,如果有更好的方法,请耐心等待