標籤:use com 簡介 bsp can ide org 流程 expect
非同步作業知識
在js世界中, 非同步作業非常流行, nodejs就是特點基於非同步非阻塞。
js語言支援的非同步文法包括, Promise async await generator yield。
這些文法需要使用者瞭解非常清楚, 往往很困難。
下面介紹一個非同步作業的超級庫,可以實現很多非同步作業和流程式控制制。
async庫
http://caolan.github.io/async/index.html
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with Node.js and installable via npm install --save async, it can also be used directly in the browser.
瀏覽器也可以用!!!
Async provides around 70 functions that include the usual ‘functional‘ suspects (map, reduce, filter, each…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). All these functions assume you follow the Node.js convention of providing a single callback as the last argument of your asynchronous function -- a callback which expects an Error as its first argument -- and calling the callback once.
包括70個非同步函數, 包括 函數類型的 map reduce filter
以及 非同步控制流程函數 parallel series
DEMO
async.map([‘file1‘,‘file2‘,‘file3‘], fs.stat, function(err, results) { // results is now an array of stats for each file});async.filter([‘file1‘,‘file2‘,‘file3‘], function(filePath, callback) { fs.access(filePath, function(err) { callback(null, !err) });}, function(err, results) { // results now equals an array of the existing files});async.parallel([ function(callback) { ... }, function(callback) { ... }], function(err, results) { // optional callback});async.series([ function(callback) { ... }, function(callback) { ... }]);
parallel 並存執行,效率高。 === Promise.all
series 按照前後順序執行。
race 競態執行。 === Promise.race
Javascript async非同步作業庫簡介