使用 Promises 編寫更好的 JavaScript 代碼

來源:互聯網
上載者:User

你可能已經無意中聽說過 Promises 是多麼的代表未來。所有酷孩子們都使用它們,但你不知道為什麼它們如此特別。難道你不能使用回調嗎?有什麼了不起的?在本文中,我們將看看promises是什麼以及如何使用它們寫出更好的JavaScript。

Promises易於閱讀

比如說我們想從HipsterJesus的API中抓取一些資料並將這些資料添加到我們的頁面中。這些API的響應資料形式如下:

 
  1. {  
  2.   "text": "<p>Lorem ipsum...</p>",  
  3.   "params": {  
  4.     "paras": 4,  
  5.     "type": "hipster-latin" 
  6.   }}  

要使用回調的話,我們通常要寫如下形式的東西:

 
  1. $.getJSON('http://hipsterjesus.com/api/', function(data) {  
  2.   $('body').append(data.text);  
  3. });  

如果你有jQuery的使用經曆,你會認出我們建立了一個GET請求並且希望響應內容是JSON。我們還傳遞了一個回呼函數來接受響應的JSON,以將資料添加到文檔中。

另外一種書寫方法是使用getJSON方法返回的promise對象。你可以直接在這個返回對象上綁定一個回調。

 
  1. var promise = $.getJSON('http://hipsterjesus.com/api/');promise.done(function(data) {  
  2.   $('body').append(data.text);  
  3. });  

在上面的回調例子中,當響應成功時它將API請求的結果添加到文檔中。但當響應失敗是會發生什麼呢?我們可以在我們的promise上綁定一個失敗處理器。

 
  1. var promise = $.getJSON('http://hipsterjesus.com/api/');promise.done(function(data) {  
  2.   $('body').append(data.text);});promise.fail(function() {  
  3.   $('body').append('<p>Oh no, something went wrong!</p>');  
  4. });  

大多數人刪掉了promise變數,這樣更簡潔,一眼就能看出代碼的作用。

 
  1. $.getJSON('http://hipsterjesus.com/api/').done(function(data) {  
  2.   $('body').append(data.text);}).fail(function() {  
  3.   $('body').append('<p>Oh no, something went wrong!</p>');  
  4. });  

jQuery也包含一個一直發生的事件處理器,不論請求成功失敗都會被調用。

 
  1. $.getJSON('http://hipsterjesus.com/api/').done(function(data) {  
  2.   $('body').append(data.text);}).fail(function() {  
  3.   $('body').append('<p>Oh no, something went wrong!</p>');}).always(function() {  
  4.   $('body').append('<p>I promise this will always be added!.</p>');  
  5. });  

通過使用promise,回調的順序是按預期的。我們能確保正常回調先被調用,然後是失敗回調,最後是一直發生的回調。

更好的API

比如說我們想創造一個HipsterJesus API的封裝對象。我們會添加一個方法——html,它將來自API的HTML資料返回。與之前設定一個回調處理器來解析請求不同,我們可以讓方法返回一個promise對象。

 
  1. var hipsterJesus = {  
  2.   html: function() {  
  3.     return $.getJSON('http://hipsterjesus.com/api/').then(function(data) {  
  4.       return data.text;  
  5.     });  
  6.   }};  

這個做法很酷,這樣我們可以繞過promise對象而不必擔心何時或如何解析它的值。任何需要promise傳回值的代碼只需註冊一個成功響應回調即可。

then方法允許我們修改promise的結果並將其傳遞給鏈中的下一個處理器。這意味現在我們可以這樣使用新的API:

 
  1. hipsterJesus.html().done(function(html) {  
  2.   $("body").append(html);  
  3. });  

直到最近,AngularJS出現了一個殺手級特性,模板可以直接綁定到promise。在Angular的控制器中,像這樣:

 
  1. $scope.hipsterIpsum = $http.get('http://hipsterjesus.com/api/');  

這樣,在模板中寫{{ hipsterIpsum.text }}就很簡單了。當promise解析後,Angular不需要自動更新視圖。不幸的是Angular團隊已經放棄了這一特性。現在,它可以通過調用$parseProvider.unwrapPromises(true)來啟用。我希望Angular已經其他架構一直包含此特性我會一直留意)。

promise最出彩的部分是你可以將它們串聯起來。比如說我們想添加一個方法到一個返回一段數組的API。

 
  1. var hipsterJesus = {  
  2.  
  3.   html: function() {  
  4.     return $.getJSON('http://hipsterjesus.com/api/').then(function(data) {  
  5.       return data.text;  
  6.     });  
  7.   },  
  8.  
  9.   paragraphs: function() {  
  10.     return this.html().then(function(html) {  
  11.       return html.replace(/<[^>]+>/g, "").split("");  
  12.     });  
  13.   }};  

我們以上面的方式這種HTML方法,我們用它在paragraphs方法中。因為promise回呼函數的傳回值將傳遞給鏈中的下一個回調,我們能夠在通過它們時自由地建立小的、功能性的方法來改變資料。

我們可以按需求任意次串聯promise。讓我們添加一個。

 
  1. var hipsterJesus = {  
  2.  
  3.   html: function() {  
  4.     return $.getJSON('http://hipsterjesus.com/api/').then(function(data) {  
  5.       return data.text;  
  6.     });  
  7.   },  
  8.  
  9.   paragraphs: function() {  
  10.     return this.html().then(function(html) {  
  11.       return html.replace(/<[^>]+>/g, "").split("");  
  12.     });  
  13.   },  
  14.  
  15.   sentences: function() {  
  16.     return this.paragraphs().then(function(paragraphs) {  
  17.       return [].concat.apply([], paragraphs.map(function(paragraph) {  
  18.         return paragraph.split(/. /);  
  19.       }));  
  20.     });  
  21.   }};  
多個調用
 

可能promise最顯著的特點是調用多個API的能力。當使用回調時,如果你需要同時建立兩個API調用時會發生什麼呢?你可能會這樣寫:

 
  1. var firstData = null;var secondData = null;var responseCallback = function() {  
  2.  
  3.   if (!firstData || !secondData)  
  4.     return;  
  5.  
  6.   // do something}$.get("http://example.com/first", function(data) {  
  7.   firstData = data;  
  8.   responseCallback();});$.get("http://example.com/second", function(data) {  
  9.   secondData = data;  
  10.   responseCallback();  
  11. });  

使用promise的話,這就簡單多了:

 
  1. var firstPromise = $.get("http://example.com/first");  
  2. var secondPromise = $.get("http://example.com/second");  
  3. $.when(firstPromise, secondPromise).done(function(firstData, secondData) {  
  4.   // do something  
  5. });  

這裡我們使用when方法,將其綁定到一個供兩個請求都完成時調用的處理器上。

結論

這就是promise。希望你馬上就想到一些可以用promise實現的的可怕的事情。你最喜歡使用它們的方式是什嗎?在評論中告訴我吧!

*註:為簡單起見,本文使用了jQuery的延期執行。jQuery的Deferred對象和Promises/A+的規範間有細微的差別,這個規範更標準。更多資訊,查看jQuery維基上的問答。

英文原文:Write Better JavaScript with Promises

譯文連結:http://www.oschina.net/translate/write-javascript-promises

聯繫我們

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