好久没写东西了,感觉自己不是那么的忙,却又没有的时间来,写自己的小心得,今天分享一下,关于顺序执行异步函数的方法,因为有些时侯无法确定哪个异步函数先执行完。下面一些方法希望对你有帮助。
一、 自定义函数:
<pre>
oneByOne: function (arr, index, callback) {
var me = this;
if (index >= arr.length) {
callback && callback();
return;
}
arr[index](function () {
me.oneByOne(arr, ++index,callback);
})
}
</pre>
二、nodejs 的async模块
- 串行无关联(series)
<pre>
var async = require('async');
console.time('series');
async.series({
one: function(callback) {
callback(null, 'one');//callback('i am err','one');异常处理
},
two: function(callback) {
callback(null, 'two');
},
}, function(error, result) {
//最后结果
console.log('error: ' + error);
console.log('result: ' + result);
console.timeEnd('series');
})
</pre>
2.串行有关联(waterfall)累似于管道符(“|”)把上一个结果做为下一个函数的输入。
<pre>
var async = require('async');
console.time('waterfall');
async.waterfall([
function(callback) {
callback(null, 'one');
},
function(onearg, callback) {
callback(null, onearg + '>>>two');
},
function(twoarg, callback) {
callback(null, twoarg + '>>>three');
},
function(threearg, callback) {
callback(null, threearg + '>>>four');
}
], function(error, result) {
console.log('error: ' + error);
console.log('result: ' + result);
console.timeEnd('waterfall');
});
</pre>
- 并行无关联(parallel)传给最终callback的数组中的数据按照tasks中声明的顺序不是完成顺序。
<pre>
var async = require('async');
console.time('parallel');
async.parallel({
one: function(callback) {
//处理逻辑
callback(null, 'one');
},
two: function(callback) {
//处理逻辑
callback(null, 'tow');
},
three: function(callback) {
//处理逻辑
callback(null, 'three');
},
four: function(callback) {
//处理逻辑
callback(null, 'four');
}
}, function(error, result) {
console.log('one:', result.one);
console.log('two:', result.two);
console.log('three:', result.three);
console.log('four:', result.four);
console.log('error: ' + error);
console.log('result: ' + JSON.stringify(result));
console.timeEnd('parallel');
});
</pre>
- 串并行混合执行(auto)1与2可以并行执行,3需要等1和2完成,4要等3完成。
<pre>
var async = require('async');
console.time('auto');
async.auto({
getData: function(callback) {
setTimeout(function() {
console.log('1.1: got data');
callback(null, 'mydata');
}, 300);
},
makeFolder: function(callback) {
setTimeout(function() {
console.log('1.1: made folder');
callback(null, 'myfolder');
}, 200);
},
writeFile: ['getData', 'makeFolder', function(callback) {
setTimeout(function() {
console.log('1.1: wrote file');
callback(null, 'myfile');
}, 300);
}],
emailFiles: ['writeFile', function(callback, results) {
console.log('emailed file: ', results.writeFile);
callback(null, results.writeFile);
}]
}, function(err, results) {
console.log('err: ', err);
console.log('results: ', results);
console.timeEnd('auto');
})
</pre>
网友评论