巢狀異步回調導致代碼非線性、耦合度高、難維護。多重 AJAX 依賴時出現「回調金字塔」。
var showMsg = function() {
var promise = new E.Promise(); // 1. 建構 Promise
setTimeout(function() {
alert('hello');
promise.resolve('done'); // 2. 成功狀態 + 傳遞資料
}, 5000);
return promise; // 3. 返回 Promise
};
// 使用 then 添加回調 (鏈式、分離關注點)
showMsg().then(function(str) {
callback(str); // str = 'done'
});
E.ajax({ url: 'test1.php', type: 'GET' })
.then(
function() { /* 成功回調 */ },
function() { /* 失敗回調 */ }
);
var requests = E.when(
E.ajax({ url: 'test1.php', type: 'GET' }),
E.ajax({ url: 'test2.php', type: 'GET' })
);
requests.then(
function(arg1, arg2) {
console.log('success: ' + arg1[0] + arg2[0]);
},
function(arg1, arg2) {
console.log('failure: ' + arg1 + arg2);
}
);
when 等待所有 Promise 進入 Resolved 才觸發成功回調;任一 Rejected 立即觸發失敗回調。
| 庫 | 核心類別 | 特色 | 易用性 |
|---|---|---|---|
| easy.js | E.Promise | API 簡潔、when 併發控制 | ★★★★★ |
| jQuery | $.Deferred / $.when | 功能完整但 API 複雜、使用率低 | ★★☆☆☆ |
| Dojo | dojo/Deferred | 早期實作、AMD 模組化 | ★★★☆☆ |
| 原生 ES6 | Promise | 標準化、瀏覽器原生、async/await 語法糖 | ★★★★★ |
Promise 模式為 CommonJS Promise/A+ 規範 核心內容。現代開發建議:
Promise + async/awaites6-promise polyfillPromise.all() / Promise.race() / Promise.allSettled().catch() 統一處理「Promise 讓異步代碼讀起來像同步代碼,這是它最大的價值。」