nodejs之async.auto

nodejs最具有魅力的地方就是它的异步处理机制,不得不承认正是因为有了它,才能做到无限量的并发,但是异步无阻塞的操作也使得我们要做一些需要顺序执行的业务逻辑时,会显得十分棘手,

直到我了解到了async库,才知道我以前写的代码是有多么的怂,而async最强大之处就在于async.auto这个方法,那么我们就简单介绍一下这个方法,

先来看代码

async.auto({
  func1:function(cb,res){
    console.log("first");
    cb(null);
  },
  func2:function(cb,res){
    console.log("second");
    cb(null);
  },
  func3:function(cb,res){
    console.log("third");
    cb(null);
  },
  func4:function(cb,res){
    console.log("forth");
    cb(null);
  }
},function(err,res){
});

在上面的代码中,async.auto中的4个方法是异步的,所以输出的顺序并不是从上往下的,所以这里我就不说输出顺序了,因为我也不知道它是会如何输出......

那么如果我一定要顺序输出,要怎么做呢?

看下面代码

async.auto({
  func1:function(cb,res){
    console.log("first");
    cb(null);
  },
  func2:['func1',function(cb,res){
    console.log("second");
    cb(null);
  }],
  func3:['func2',function(cb,res){
    console.log("third");
    cb(null);
  }],
  func4:['func3',function(cb,res){
    console.log("forth");
    cb(null);
  }]
},function(err,res){
});

这样的话,4个方法之间就会产生依赖,它们就会按照顺序往下执行,

好,那么问题就来了,现在我的业务逻辑是func1与func2可以同步执行,func3必须要依赖func1,func4必须依赖func2与func3,想想是不是有点复杂了呢?

当然你可以先自己试试怎么写,然后再看看接下来我写的代码,看看我写的方法有木有区别

async.auto({
  func1:function(cb,res){
    console.log("first");
    cb(null);
  },
  func2:function(cb,res){
    console.log("second");
    cb(null);
  },
  func3:['func1',function(cb,res){
    console.log("third");
    cb(null);
  }],
  func4:['func2','func3',function(cb,res){
    console.log("forth");
    cb(null);
  }]
},function(err,res){
});

想必这个异步操作顺序应该很好理解吧

相比于其他的类库来说,async.auto更好理解一点

另外async.auto还有一个特点,就是每一个cb都会传入一个res参数,让你得到上一个函数的执行结果,当然,如果上一个函数不存在或是在你执行之后,那就不会有结果了,你不需要手动地将结果存入对象,async.auto就会帮你做好这件事情,是不是很神奇啊,哈哈

转载于:https://my.oschina.net/codingBingo/blog/710040

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值