我试图使用Async Node.js模块依次执行2个循环,第一个循环。

async.series([
    insertSkill,//first loop
    insertBehaviours//second loop
], function(err, results){
        console.log(results);//print results
    });


这是每个函数中的代码,我删除了一些代码以提高可读性

function insertSkill(fnCallback){
    async.eachSeries(Object.keys(behaviours), function (aSkill, callback){
        if (aSkill.indexOf('skillid') > -1) {
            if (behaviours[aSkill] == null || behaviours[aSkill] == "") {}

            connection.get().query('SELECT skill_id FROM skills WHERE skill_id = ?', num, function (err, skillResults) {

                if (skillTitle != null || skillTitle != "") {

                    connection.get().query('INSERT INTO skills SET ?', [skill], function (err, skillResults) {

                        if (err) {}
                     else {
                            console.log("1");//PRINTING AFTER 2, DONT WANT THAT!!!                        }
                    });
                }
            });
        }
        callback(null);
    },fnCallback);
}


第二功能

//Second Function
function insertBehaviours(fnCallback){
    async.eachSeries(Object.keys(behaviours), function (aBehaviour, secondCallback) {
        if (aBehaviour.indexOf('behaviourid') > -1) {
            if (behaviours[aBehaviour] == null || behaviours[aBehaviour] == "") {
            console.log("2");//PRINTING BEFORE 1, DONT WANT THAT!!!

                });
            }
        }
        secondCallback(null);
    },fnCallback);
}


问题是,第二个功能insertBehaviours在insertSkills之前首先发生。我希望insertSkills首先发生,然后才发生insertBehaviours

最佳答案

原因是您的第一个函数,insertSkill中有几个异步方法。但是,您要在迭代器上调用回调,然后这些方法才有机会完成。您的insertSkill方法应该更像这样:

function insertSkill(fnCallback){
    async.eachSeries(Object.keys(behaviours), function (aSkill, callback){
        if (aSkill.indexOf('skillid') > -1) {
            if (behaviours[aSkill] == null || behaviours[aSkill] == "") {}

            connection.get().query('SELECT skill_id FROM skills WHERE skill_id = ?', num, function (err, skillResults) {

                if (skillTitle != null || skillTitle != "") {

                    connection.get().query('INSERT INTO skills SET ?', [skill], function (err, skillResults) {

                        if (err) {}
                     else {
                            console.log("1");//PRINTING AFTER 2, DONT WANT THAT!!!
                            callback(null); // notice I moved this.
                          }
                    });
                }
            });
        }
    },fnCallback);
}


因为这只会在两个SQL语句运行后才调用callback函数。

09-25 18:06