1. 承諾鏈 promise chaining
(1). 語法:
- promise.then().then()...
如:// 通過學生學號獲取學生信息
function findStudent(studentID) {
return new Promise( (complete, failed) => {
setTimeout( () => {
complete( {
studentID,
name: 'Lulu'
} );
}, 2000 ); // 用setTimeout來模擬從數據庫調數據的延遲時間
});
};
// 通過學生姓名獲得學生課程
function getCourses(student) {
return new Promise( (complete, failed) => {
console.log(`Get ${student.name}'s courses...`);
setTimeout( () => {
complete(['Math', 'React', 'JavaScript']);
},2000 );
} );
};
// 計算學生的縂課程數
function totalCourses(courses) {
return new Promise( (complete, failed) => {
console.log('Calculate all the courses.');
setTimeout( () => {
complete(courses.length);
}, 2000 );
} );
};
// 使用承諾鏈獲得結果
findStudent(19).then(getCourses).then(totalCourses).then(console.log);
// Get Lulu's courses...
// Calculate all the courses.
// 3
2. Promise.all() 方法
- 只有當所有的promise都正常完成時,promise.all()方法會把所有的結果打包成一個數組array,並返回該數組。然而,一旦有一個promise失敗后,promise.all()方法會直接返回失敗的理由,並不再繼續等待其他promise的執行結果。所以,一般promise.all()方法可以用來匯總多個異步操作的結果。
正常完成時,如:const one = new Promise( (complete, failed) => {
setTimeout( () => {
complete(1);
}, 1000);
});
const two = new Promise( (complete, failed) => {
setTimeout( () => {
complete(2);
}, 1000);
});
// 給出所有成功的結果
Promise.all([one, two]).then(console.log); // [1, 2]
有異常時,如:const one = new Promise( (complete, failed) => {
setTimeout( () => {
complete(1);
}, 1000);
});
const two = new Promise( (complete, failed) => {
setTimeout( () => {
failed(‘失敗沒理由’);
}, 1000);
});
Promise.all([one, two]).then(console.log).catch(console.log); // 失敗沒理由
// 由於two失敗了,所以,不在意成功的結果,而是直接給出失敗的理由。