开发者

How to skip the async calls in node.js

Is there any way to skip the calls in serial or parallel calls flow.

var flow = require('flow');

    flow.exec(
       func开发者_高级运维tion(){
         //Execute
       },
       function(){
         //Skip
       },
       function(){
        //Exec
       },
       function(){
         //Done
       }
    );


Just create a condition inside the method that you might want to skip and trigger the callback immediately

flow.exec(
function taskOne() {
   // long task 
   fs.readFile(path, 'utf8', this);
},
function taskTwo() {
  if (condition) {
    return this(); // trigger the callback.
  }
},
function lastTask() {
   console.log("done");
}
);


function getUser(userId,username,callback){
    flow.exec(
            function(){
                if(userId)
                    return this(null,userId);

                redis.get('username:'+username,this);
            },
            function(err,userId){
                if(err) throw err;
                if(!userId) return callback(null);
                this.userId = userId;
                redis.hgetall('user:'+userId+':profile',this);
            },
            function(err,profile){
                if(err) throw err;
                profile.userId = this.userId;       
                callback(profile);
            }
    );
}



getUser(null,'gk',function(user){
    if(!user) console.log('not found');     
    console.log(user);  
});

Can i use like this

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜