npm安装
async 官方文档:
https://caolan.github.io/async/
学习async 异步控制模块; 最好的还是看官方文档,因为模块版本更新快!
控制流 方法
auto :
auto(tasks, concurrencyopt, callbackopt)
1. tasks中的每个函数,可以根据它自身的要求来定义执行的顺序。每个函数可以选择在他执行之前必须要执行的函数;当然也可以不指定。
2. 如果tasks中的一个函数发生了错误,产生了错误信息err ;那么tasks这个执行序列就会停止,其他还没执行的函数就不执行,依赖它先执行的函数们就更不会执行了。并且callback会立即被调用参数就是err。
3. tasks中的函数,参数要么是一个,那么是两个;如果它有依赖其他函数那么第一个参数是依赖函数的结果集;如果没有依赖,那么它只有一个参数就是callback
例子:
var async = require('async');
var fs = require('fs');
var callback = function (err, results) {
console.log(results);
};
async.auto({
// this function will just be passed a callback
readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
showData: ['readData', function(results, cb) {
// results.readData is the file's contents
// ...
cb(null,results);
}]
}, callback);
async.auto({
get_data: function(callback) { //最后那个参数就是 callback
console.log('in get_data');
// async code to get some data
callback(null, 'data', 'converted to array');
},
make_folder: function(callback) {
console.log('in make_folder');
// async code to create a directory to store a file in
// this is run at the same time as getting the data
callback(null, 'folder');
},
write_file: ['get_data', 'make_folder', function(results, callback) {
console.log('in write_file', JSON.stringify(results));
// once there is some data and the directory exists,
// write the data to a file in the directory
callback(null, 'filename');
}],
email_link: ['write_file', function(results, callback) {
console.log('in email_link', JSON.stringify(results));
// once the file is written let's email a link to it...
// results.write_file contains the filename returned by write_file.
callback(null, {'file':results.write_file, 'email':'user@example.com'});
}]
}, function(err, results) {
console.log('err = ', err);
console.log('results = ', results);
});
async.auto({
getData: function(callback){
setTimeout(function(){
console.log('got data');
callback(null, 'mydata');
}, 300);
},
makeFolder: function(callback){
setTimeout(function() {
console.log('made folder');
callback(null, 'myfolder');
}, 200);
},
writeFile:['getData', 'makeFolder', function(results,callback){
setTimeout(function () {
console.log('write file');
callback(null, 'myfile');
}, 300);
}],
emailFiles: ['writeFile', function(results, callback){
console.log('send email');
callback(null, results.writeFile);
}]
},function(err, results){
console.log(err); //->null
console.log(results);
//made folder
//got data
//write file
//send email
/*
results{
makeFolder: 'myfolder',
getData: 'mydata',
writeFile: 'myfile',
emailFiles: 'myfile'
}
*/
});