Javascript async非同步作業庫簡介

來源:互聯網
上載者:User

標籤: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非同步作業庫簡介

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.