異步回調層層嵌套導致代碼難以維護(回調地獄)。建造者模式透過鏈式調用,將異步流程扁平化。
function getBeerById(id, callback) {
_request('GET', 'URL' + id, function(res) {
callback(res.responseText);
});
}
// 傳統橋接寫法
function getBeerByIdBridge() {
getBeerById(id, function(res) {
alert(res.toString());
});
// doAnotherThing();
}
var el = document.querySelector('#test');
el.addEventListener('click', getBeerByIdBridge, false);
class BeerRequestBuilder {
constructor(id) {
this.id = id;
this.callbacks = [];
}
onSuccess(fn) {
this.callbacks.push({type: 'success', fn});
return this; // 鏈式調用
}
onError(fn) {
this.callbacks.push({type: 'error', fn});
return this;
}
execute() {
getBeerById(this.id, (res) => {
this.callbacks.filter(c => c.type === 'success')
.forEach(c => c.fn(res));
});
}
}
// 使用
new BeerRequestBuilder(123)
.onSuccess(res => alert(res))
.onError(err => console.error(err))
.execute();
本質上是將回調函數集合化、延遲執行,是 Promise/async-await 的前身思想。