優化非同步操作的一個物件。
Promise 物件
有三種狀態 :
- pending – 未確認(初始狀態)
- fulfilled – 事件實現
- rejected – 事件失敗
而在建立 Promise 物件時,會有兩個參數 :
- resolve – 在Promise 物件的狀態變為 fulfilled,操作成功時調用。
- reject – 在Promise 物件的狀態變為 rejected,操作失敗時調用。
建立Promise 物件
1 2 3 4 5 6 7
| var promiseFn = new Promise(function (resolve, reject) { if (操作成功) { resolve(); } else { reject(); } });
|
Promise 物件原型方法
Promise.prototype.then()
then() 方法接受兩個分別要執行的參數 :
- 第一個參數是當 Promise 狀態變為fulfilled時調用。
- 第二個函數是當 Promise 狀態變為rejected時調用(選擇性)。
1 2 3 4
| promiseFn.then( (resolve) =>{...}, (reject) => {...} )
|
Promise.prototype.catch()
catch() 方法用來綁定當Promise 狀態變為rejected 狀態時,要執行的參數。
1 2 3 4 5
| promiseFn.then( (resolve) =>{...} ).catch( (reject) => {...} )
|
使用 return 來串接
後面的 then() 會接收前一個 then() 的 return value 當作參數。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| let text = document.getElementById('text');
function promiseFn(num) { return new Promise(function (resolve, reject) { if (num >= 10) { resolve(`成功投幣 ${num} 元`); } else { reject(`投幣 ${num} 元,金額不足`); } }); }
promiseFn(5).then( (res) => { console.log(res); return res }, (rej) => { console.log(rej); // 投幣 5 元,金額不足 return rej } ).then( (res) => { text.textContent = res; }, (rej) => { text.textContent = rej; // 投幣 5 元,金額不足 } )
|
Promise.all
透過陣列形式傳入多個promise物件。
所有 Promise 物件個別的返回值,會被組成一個陣列。
若其中一個 Promise 物件狀態變為 rejected,則回傳reject 的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| Promise.all([promiseFn(15),promiseFn(20),promiseFn(35)]).then( (res) => { console.log(res); // ["成功投幣 15 元", "成功投幣 20 元", "成功投幣 35 元"] return res }, (rej) => { console.log(rej); return rej } ).then( (res) => { text.textContent = res; // 成功投幣 15 元,成功投幣 20 元,成功投幣 35 元 }, (rej) => { text.textContent = rej; } )
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| Promise.all([promiseFn(15),promiseFn(5),promiseFn(35)]).then( (res) => { console.log(res); return res }, (rej) => { console.log(rej); // 投幣 5 元,金額不足 return rej } ).then( (res) => { text.textContent = res; }, (rej) => { text.textContent = rej; // 投幣 5 元,金額不足 } )
|
Promise.race
Promise.race() 一樣透過陣列形式傳入多個promise物件,不同的是取回第一個改變狀態promise物件的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| Promise.race([promiseFn(15),promiseFn(5),promiseFn(35)]).then( (res) => { console.log(res); return res }, (rej) => { console.log(rej); // 成功投幣 15 元 return rej } ).then( (res) => { text.textContent = res; }, (rej) => { text.textContent = rej; // 成功投幣 15 元 } )
|