简体   繁体   中英

Async flow in node.js

In my node.js application i want to make my flow synchronous. I faced this kind of issues previously, i solved it. But now i am struggling now in this situation.

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

In the above code if(condition) satisfied then the findById(which is async) is called and the Callback(); after that is called before its executes.

My flow should be if it entered into if condition the fetching should be done and then only the next loop should rotate.

Please share your ideas. thanks in advance.

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

the else is added there because your app.models.Schedule.findById has a callback function(err, res) which lets the bottom Callback() be called before even getting to the function(err,res) part.

so here is an example

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

Whats the order of the letters printed here??

Its A, C then B

The example here is of setTimeout but it can be anyother function with a callback implemented.

There is no async.forEach , and you can get rid of for loop

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM