2016-06-11 49 views
0

我想在系列中執行2個循環,其中1個使用異步Node.js模塊之前。Node.js異步系列不按順序工作

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

回答

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

正如只會調用callback功能,一旦你兩個SQL語句已經運行。

+0

非常感謝你mrwillihog,這解決了我的問題! – user3044002