Javascript 中的神器

來源:互聯網
上載者:User

標籤:英語   generic   else   new   get   ati   有一個   mic   狀態改變   

Promise in js

回呼函數真正的問題在於他剝奪了我們使用 return 和 throw 這些關鍵字的能力。而 Promise 很好地解決了這一切。

2015 年 6 月,ECMAScript 6 的正式版 終於發布了。

ECMAScript 是 JavaScript 語言的國際標準,JavaScript 是 ECMAScript 的實現。ES6 的目標,是使得 JavaScript 語言可以用來編寫大型的複雜的應用程式,成為企業級開發語言。

概念

ES6 原生提供了 Promise 對象。

所謂 Promise,就是一個對象,用來傳遞非同步作業的訊息。它代表了某個未來才會知道結果的事件(通常是一個非同步作業),並且這個事件提供統一的 API,可供進一步處理。

Promise 對象有以下兩個特點。

(1)對象的狀態不受外界影響。Promise 對象代表一個非同步作業,有三種狀態:Pending(進行中)、Resolved(已完成,又稱 Fulfilled)和 Rejected(已失敗)。只有非同步作業的結果,可以決定當前是哪一種狀態,任何其他動作都無法改變這個狀態。這也是 Promise 這個名字的由來,它的英語意思就是「承諾」,表示其他手段無法改變。

(2)一旦狀態改變,就不會再變,任何時候都可以得到這個結果。Promise 對象的狀態改變,只有兩種可能:從 Pending 變為 Resolved 和從 Pending 變為 Rejected。只要這兩種情況發生,狀態就凝固了,不會再變了,會一直保持這個結果。就算改變已經發生了,你再對 Promise 對象添加回呼函數,也會立即得到這個結果。這與事件(Event)完全不同,事件的特點是,如果你錯過了它,再去監聽,是得不到結果的。

有了 Promise 對象,就可以將非同步作業以同步操作的流程表達出來,避免了層層嵌套的回呼函數。此外,Promise 對象提供統一的介面,使得控制非同步作業更加容易。

Promise 也有一些缺點。首先,無法取消 Promise,一旦建立它就會立即執行,無法中途取消。其次,如果不設定回呼函數,Promise 內部拋出的錯誤,不會反應到外部。第三,當處於 Pending 狀態時,無法得知目前進展到哪一個階段(剛剛開始還是即將完成)。

 1  (/* 非同步作業成功 */){ 2  resolve(value); 3  } else { 4  reject(error); 5  } 6 }); 7  8 promise.then(function(value) { 9  // success10 }, function(value) {11  // failure12 });

Promise 建構函式接受一個函數作為參數,該函數的兩個參數分別是 resolve 方法和 reject 方法。

如果非同步作業成功,則用 resolve 方法將 Promise 對象的狀態,從「未完成」變為「成功」(即從 pending 變為 resolved);

如果非同步作業失敗,則用 reject 方法將 Promise 對象的狀態,從「未完成」變為「失敗」(即從 pending 變為 rejected)。

基本的 api
  1. Promise.resolve()
  2. Promise.reject()
  3. Promise.prototype.then()
  4. Promise.prototype.catch()
  5. Promise.all() // 所有的完成

    ll([p1,p2,p3]);
  6. Promise.race() // 競速,完成一個即可進階進階

    promises 的奇妙在於給予我們以前的 return 與 throw,每個 Promise 都會提供一個 then() 函數,和一個 catch(),實際上是 then(null, ...) 函數,

    omePromise().then(functoin(){        // do something    });

    我們可以做三件事,

    1. return 另一個 promise2. return 一個同步的值 (或者 undefined)3. throw 一個同步異常 ` throw new Eror(‘‘);`
    1. 封裝同步與非同步代碼
    ```new Promise(function (resolve, reject) { resolve(someValue); });```寫成```Promise.resolve(someValue);```
    2. 捕獲同步異常
    new Promise(function (resolve, reject) { throw new Error(‘悲劇了,又出 bug 了‘); }).catch(function(err){ console.log(err); });

    如果是同步代碼,可以寫成

     Promise.reject(new Error("什麼鬼"));
    3. 多個異常捕獲,更加精準的捕獲
    somePromise.then(function() { return a.b.c.d();}).catch(TypeError, function(e) { //If a is defined, will end up here because //it is a type error to reference property of undefined}).catch(ReferenceError, function(e) { //Will end up here if a wasn‘t defined at all}).catch(function(e) { //Generic catch-the rest, error wasn‘t TypeError nor //ReferenceError});
    4. 擷取兩個 Promise 的傳回值
    1. .then 方式順序調用2. 設定更高層的範圍3. spread
    5. finally
    任何情況下都會執行的,一般寫在 catch 之後
    6. bind
    omethingAsync().bind({}).spread(function (aValue, bValue) { this.aValue = aValue; this.bValue = bValue; return somethingElseAsync(aValue, bValue);}).then(function (cValue) {     return this.aValue + this.bValue + cValue;});

    或者 你也可以這樣

    var scope = {};somethingAsync().spread(function (aValue, bValue) { scope.aValue = aValue; scope.bValue = bValue; return somethingElseAsync(aValue, bValue);}).then(function (cValue) { return scope.aValue + scope.bValue + cValue;});

    然而,這有非常多的區別,

    1. 你必須先聲明,有浪費資源和記憶體泄露的風險
    2. 不能用於放在一個運算式的上下文中
    3. 效率更低
    7. all。非常用于于處理一個動態大小均勻的 Promise 列表8. join。非常適用於處理多個分離的 Promise
    ```var join = Promise.join;join(getPictures(), getComments(), getTweets(), function(pictures, comments, tweets) { console.log("in total: " + pictures.length + comments.length + tweets.length);});```
    9. props。處理一個 promise 的 map 集合。只有有一個失敗,所有的執行都結束
    ```Promise.props({ pictures: getPictures(), comments: getComments(), tweets: getTweets()}).then(function(result) { console.log(result.tweets, result.pictures, result.comments);});```
    10. any 、some、race
    ```Promise.some([ ping("ns1.example.com"), ping("ns2.example.com"), ping("ns3.example.com"), ping("ns4.example.com")], 2).spread(function(first, second) { console.log(first, second);}).catch(AggregateError, function(err) {err.forEach(function(e) {console.error(e.stack);});});;```有可能,失敗的 promise 比較多,導致,Promsie 永遠不會 fulfilled
    11. .map(Function mapper [, Object options])
    用於處理一個數組,或者 promise 數組,

    Option: concurrency 並發現

        map(..., {concurrency: 1});

    以下為不限制並發數量,讀書檔案資訊

    Promise = require("bluebird");var join = Promise.join;var fs = Promise.promisifyAll(require("fs"));var concurrency = parseFloat(process.argv[2] || "Infinity");var fileNames = ["file1.json", "file2.json"];Promise.map(fileNames, function(fileName) { return fs.readFileAsync(fileName) .then(JSON.parse) .catch(SyntaxError, function(e) { e.fileName = fileName; throw e; })}, {concurrency: concurrency}).then(function(parsedJSONs) { console.log(parsedJSONs);}).catch(SyntaxError, function(e) { console.log("Invalid JSON in file " + e.fileName + ": " + e.message);});結果$ sync && echo 3 > /proc/sys/vm/drop_caches$ node test.js 1reading files 35ms$ sync && echo 3 > /proc/sys/vm/drop_caches$ node test.js Infinityreading files: 9ms
    11. .reduce(Function reducer [, dynamic initialValue]) -> Promise
    Promise.reduce(["file1.txt", "file2.txt", "file3.txt"], function(total, fileName) { return fs.readFileAsync(fileName, "utf8").then(function(contents) { return total + parseInt(contents, 10); });}, 0).then(function(total) { //Total is 30});
    12. Time
    1. .delay(int ms) -> Promise
    2. .timeout(int ms [, String message]) -> Promise
    Promise 的實現
    1. q
    2. bluebird
    3. co
    4. when
    ASYNC

    async 函數與 Promise、Generator 函數一樣,是用來取代回呼函數、解決非同步作業的一種方法。它本質上是 Generator 函數的文法糖。async 函數並不屬於 ES6,而是被列入了 ES7。

Javascript 中的神器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.