你大概已經聽過 Promises,身邊的人都在談它、用它,但始終不清楚它到底特別在哪。回呼函式不是也能解決嗎?本文就來把 Promise 是什麼、以及它如何讓非同步程式碼變得可讀,一次講清楚。
假設要從 HipsterJesus 這類 API 抓取資料並插入頁面,回傳格式如下:
{
"text": "<p>Lorem ipsum...</p>",
"params": { "paras": 4, "type": "hipster-latin" }
}
用純回呼的寫法:
$.getJSON('https://hipsterjesus.com/api/', function(data) {
$('body').append(data.text);
});
另一種寫法是利用 getJSON 回傳的 promise 物件,直接在它上面掛回呼:
var promise = $.getJSON('https://hipsterjesus.com/api/');
promise.done(function(data) {
$('body').append(data.text);
});
如果請求失敗呢?可以在同一個 promise 上再掛一個失敗處理器:
promise.fail(function() {
$('body').append('<p>Oh no, something went wrong!</p>');
});
實務上大家通常不保留中間變數,直接串起來,一眼就看懂意圖:
$.getJSON('https://hipsterjesus.com/api/')
.done(function(data) { $('body').append(data.text); })
.fail(function() { $('body').append('<p>Oh no, something went wrong!</p>'); });
jQuery 還提供 always(),不論成功失敗都會執行:
$.getJSON('https://hipsterjesus.com/api/')
.done(function(data) { $('body').append(data.text); })
.fail(function() { $('body').append('<p>Oh no, something went wrong!</p>'); })
.always(function() { $('body').append('<p>I promise this will always be added!</p>'); });
用 promise 有個隱形好處:回呼的執行順序是可控的。你能確定成功回呼先跑、失敗回呼次之、always 最後收尾。
假設要封裝一個物件,其中 html 方法回傳 API 的 HTML 片段。與其要求呼叫方自己傳回呼進來,不如讓方法直接回傳 promise:
var hipsterJesus = {
html: function() {
return $.getJSON('https://hipsterjesus.com/api/').then(function(data) {
return data.text;
});
}
};
這樣呼叫方可以把 promise 到處傳遞,不必關心它何時、如何被解析,只需要在真正要用值的地方註冊成功回呼。then 的關鍵作用在於:它能改寫 promise 的結果並往下一棒傳。
hipsterJesus.html().done(function(html) {
$("body").append(html);
});
AngularJS 曾經有個很亮眼的特性:模板可以直接綁定 promise。控制器裡寫成 $scope.hipsterIpsum = $http.get('https://hipsterjesus.com/api/');,模板中就能直接用 {{ hipsterIpsum.text }},promise 解析後視圖自動更新。這個特性後來被移除,若要恢復需自行啟用 $parseProvider.unwrapPromises(true)。
Promise 最精彩的地方是它們可以串成一條鏈。舉例來說,想在 html 之外再加一個回傳段落陣列的方法:
var hipsterJesus = {
html: function() {
return $.getJSON('https://hipsterjesus.com/api/').then(function(data) {
return data.text;
});
},
paragraphs: function() {
return this.html().then(function(html) {
return html.replace(/<[^>]+>/g, "").split("\n\n");
});
}
};
因為 promise 回呼的返回值會往下一棒傳,我們可以自由地用小而專一的函式層層加工資料。需要的話可以一路串下去:
var hipsterJesus = {
html: function() {
return $.getJSON('https://hipsterjesus.com/api/').then(function(data) {
return data.text;
});
},
paragraphs: function() {
return this.html().then(function(html) {
return html.replace(/<[^>]+>/g, "").split("\n\n");
});
},
sentences: function() {
return this.paragraphs().then(function(paragraphs) {
return [].concat.apply([], paragraphs.map(function(paragraph) {
return paragraph.split(/. /);
}));
});
}
};
若用純回呼要同時發兩個請求、等兩邊都完成才繼續,程式碼會變成這樣:
var firstData = null;
var secondData = null;
var responseCallback = function() {
if (!firstData || !secondData) return;
// do something
};
$.get("https://example.com/first", function(data) {
firstData = data;
responseCallback();
});
$.get("https://example.com/second", function(data) {
secondData = data;
responseCallback();
});
改用 promise,只要一行 when:
var firstPromise = $.get("https://example.com/first");
var secondPromise = $.get("https://example.com/second");
$.when(firstPromise, secondPromise).done(function(firstData, secondData) {
// do something
});
它會把兩個請求綁到同一個處理器上,等兩者都完成才觸發。
這就是 Promise 的核心價值:可讀性、可串接性、以及對併發流程的簡潔表達。下次遇到多層回呼時,不妨試著改寫成鏈式結構。
附註:為求簡潔,本文使用 jQuery 的 Deferred 實作。jQuery 的 Deferred 物件與 Promises/A+ 規範之間存在細微差異,後者才是更嚴謹的標準。