JavaScript 自學筆記31

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失敗了,所以,不在意成功的結果,而是直接給出失敗的理由。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值