2016-08-26 72 views
0

在我的node.js應用程序中,我想讓流程同步。我以前遇到過這樣的問題,我解決了它。但現在我在這種情況下正在掙扎。node.js中的異步流程

for(var k=nearestMatchLength;k--;) { 
    async.forEach(matchedArray[i].nearestmatch, function(elem,Callback){ 
     if(condition){ 
      app.models.Schedule.findById(elem.Id, function(err, res){ 
      for(){ 
      };----> for loop 
      Callback(); 
      }); 
     } 
     Callback(); 
    }); 
} 

在上面的代碼if(condition)滿意則findById(which is async)叫,之後的Callback();其執行之前被調用。

我的流程應該是,如果它進入如果條件應該完成抓取,然後只有下一個循環應該旋轉。

請分享你的想法。提前致謝。

+0

的是'matchedArray [I] .nearestmatch'一個數組? – slebetman

+0

@slebetman是其數組.. – Subburaj

+0

你在尋找'else'語句嗎? –

回答

1
for(var k=nearestMatchLength;k--;) { 
    async.forEach(matchedArray[i].nearestmatch, function(elem,Callback){ 
     if(condition){ 
      app.models.Schedule.findById(elem.Id, function(err, res){ 
      for(){ 
      };----> for loop 
      Callback(); 
      }); 
     } 
     else{ 
     Callback(); 
     } 
    }); 
} 

else中有添加,因爲你的app.models.Schedule.findById有所回調function(err, res)它可以讓甚至讓到function(err,res)部分之前底部Callback()被調用。

所以這裏是一個例子

console.log('A'); 
setTimeout(function(){ 
    console.log('B'); 
    },0); 
console.log('C'); 

請告訴我在這裏打印的字母的順序??

及其A,C則B

這裏的例子是setTimeout但它可以是與實現的回調函數任何其它。

+0

另外,您可以'返回findById'而不是其他。 –

1

沒有async.forEach,你可以擺脫for

//async.times - execute fn number of times 
async.times(nearestMatchLength, function(i, next){ 
    async.each(matchedArray[i].nearestmatch, function(elem, callback){ 
     if(true){ 
      app.models.Schedule.findById(elem.Id, function(err, result){ 
      //do something async 
      //for example it's a new for loop 
      async.each([1,2,3], function(number, cb) { 
       //do some work 
       result.number = number; 
       //call cb to reach next iteration 
       cb(); 
      }, function() { 
       //all elements from [1,2,3] complete 
       //do some async again and call next to complete 
       //async.times execution 
       result.save(next); 
      }); 
      }); 
     } else { 
      next(null); 
     } 
    }); 
}, function(err, done) { 
    //complete 
});