Async:提供了大约20个函数,包括常用的 map, reduce, filter, forEach 等,
异步流程控制模式包括,串行(series),并行(parallel),瀑布(waterfall)等,
对于异常判断:一旦某个异步调用产生了异常,结束调用,并将异常作为第一个参数传入给最终的回调函数,只有所有异步调用都正常完成时,才会将结果以数组形式传入。
安装:
npm install async
var async = require('async');
console.time('series');
async.series({
one:function(callback){
setTimeout(function () {
callback(null,'one');
},100)
},
two:function (callback) {
setTimeout(function () {
callback(null,'two');
},200)
},
three:function (callback) {
setTimeout(function () {
callback(null,'three');
},300)
}
},function (error,result) {
console.log('error:'+ error);
console.log('result:'+ JSON.stringify(result));
console.timeEnd('series');
});
waterfall: 当前一个的结果是后一个调用的输入时
var async = require('async');
console.time('waterfall');
async.waterfall([
function (callback) {
setTimeout(function () {
callback(null,'one');
},100)
},
function (onearg,callback) {
setTimeout(function () {
callback(null,onearg+'>>>two');
},200)
},
function (twoarg,callback) {
setTimeout(function () {
callback(null,twoarg+'>>>three');
},300)
}
], function (error,result) {
console.log('error:'+ error);
console.log('result:'+JSON.stringify(result));
console.timeEnd('waterfall');
});
并行提升性能,
var async = require('async');
console.time('parallel');
async.parallel({
one:function(callback){
setTimeout(function () {
callback(null,'one');
},100)
},
two:function (callback) {
setTimeout(function () {
callback(null,'two');
},200)
},
three:function (callback) {
setTimeout(function () {
callback(null,'three');
},300)
}
},function (error,result) {
console.log('error:'+ error);
console.log('result:'+ JSON.stringify(result));
console.timeEnd('parallel');
});
在现实运用中,具有很多复杂的依赖关系,或是异步或是同步,auto()能根据依赖关系自动分析,以最佳的顺序执行这些业务。
学习参考:
深入浅出node
https://blog.csdn.net/qqhjqs/article/details/51913942
https://blog.csdn.net/pretent/article/details/45619503