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就会帮你做好这件事情,是不是很神奇啊,哈哈