node.js中的异步流

时间:2016-08-26 05:10:18

标签: javascript node.js asynchronous

在我的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();被调用。

我的流程应该是如果它进入,如果条件应该完成提取,然后只有下一个循环应该旋转。

请分享您的想法。提前谢谢。

2 个答案:

答案 0 :(得分: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),可以在到达Callback()部分之前调用底部function(err,res)

所以这是一个例子

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

这里印的字母的顺序是什么?

它的A,C然后是B

此处的示例是setTimeout,但它可以是实现回调的任何其他函数。

答案 1 :(得分: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
});