Node.js异步系列无法正常工作

时间:2016-06-11 03:17:36

标签: javascript node.js asynchronous sequence

我正在尝试使用Async Node.js模块执行2个循环,1个在另一个之前。

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之前发生。我想首先在insertBehaviours

之前发生insertSkills

1 个答案:

答案 0 :(得分:1)

原因是你的第一个函数,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函数。