async 提供的api包括三個部分:
(1)流程控制 常見的幾種流程控制.
(2)集合處理 異步操做處理集合中的數據.
(3)工具類 .
github 開源地址: https://github.com/caolan/asyncjavascript
async series 控制串行無關聯流程java
**方式一** async.series([ function(callback) { // do some stuff ... callback(null, 'one'); }, function(callback) { // do some more stuff ... callback(null, 'two'); } ], // optional callback function(err, results) { // results is now equal to ['one', 'two'] }); **方式二** async.series({ one: function(callback) { setTimeout(function() { callback(null, 1); }, 200); }, two: function(callback){ setTimeout(function() { callback(null, 2); }, 100); } }, function(err, results) { // results is now equal to: {one: 1, two: 2} });
async series 並行且無關聯流程git
**方式一** async.parallel([ function(callback) { setTimeout(function() { callback(null, 'one'); }, 200); }, function(callback) { setTimeout(function() { callback(null, 'two'); }, 100); } ], // optional callback function(err, results) { // the results array will equal ['one','two'] even though // the second function had a shorter timeout. }); **方式二** // an example using an object instead of an array async.parallel({ one: function(callback) { setTimeout(function() { callback(null, 1); }, 200); }, two: function(callback) { setTimeout(function() { callback(null, 2); }, 100); } }, function(err, results) { // results is now equals to: {one: 1, two: 2} });
async waterfall 串行且有關聯github
**方式一** async.waterfall([ function(callback) { callback(null, 'one', 'two'); }, function(arg1, arg2, callback) { // arg1 now equals 'one' and arg2 now equals 'two' callback(null, 'three'); }, function(arg1, callback) { // arg1 now equals 'three' callback(null, 'done'); } ], function (err, result) { // result now equals 'done' }); **方式二** // Or, with named functions: async.waterfall([ myFirstFunction, mySecondFunction, myLastFunction, ], function (err, result) { // result now equals 'done' }); function myFirstFunction(callback) { callback(null, 'one', 'two'); } function mySecondFunction(arg1, arg2, callback) { // arg1 now equals 'one' and arg2 now equals 'two' callback(null, 'three'); } function myLastFunction(arg1, callback) { // arg1 now equals 'three' callback(null, 'done'); }