0%

【JS】Promise學習筆記-進階用法

【JS】Promise學習筆記-進階用法

上次做完Promise的基本用法,接下來筆記其他的用法

▌串接多個Promise

假如我們有多個非同步的任務要執行,應該如何串接呢?
舉例,首先建立的Promise函式

1
2
3
4
5
6
7
8
9
function PromiseFn(num){
return new Promise(function(resolve,reject){
if(num>0){
resolve('成功',num);
}else{
reject('失敗',num);
}
})
}

開始串接,使用return串接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
PromiseFn(1)
.then(res => {
console.log(res);
return PromiseFn(5);
})
//繼續用then接上一個return PromiseFn(5);
.then(res => {
console.log(res);
return PromiseFn(7);
})
.then(res => {
console.log(res);
return PromiseFn(-5);
})
.catch(res => {
console.log('catch',res);
})

如果在串接的某一個function失敗的話,它會直接跳到catch,不會在執行catch
上方的串接

如何接著串接?
只要在catch內重新return一個function即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
PromiseFn(1)
.then(res => {
console.log(res);
return PromiseFn(5);
})
//繼續用then接上一個return PromiseFn(5);
.then(res => {
console.log(res);
return PromiseFn(7);
})
.then(res => {
console.log(res);
return PromiseFn(-5);
})
.catch(res => {
console.log('catch',res);
return PromiseFn(7);
})
.then(res => {
console.log(res);
return PromiseFn(100);
})

▌then可以接收成功也可以接收失敗

一般來說會使用then接收成功,catch接收失敗,但是then也可以接收失敗與成功
將then帶入兩個callback function,一個給成功時接收,一個給失敗

1
2
3
4
5
6
7
.then((res) => {
console.log(res);
return PromiseFn(100);
},(rej) => {
console.log(rej);
return PromiseFn(100);
})

▌Promise方法:Promise.all-同時執行多個請求

使用Promise.all([])帶入一個陣列,把要執行的請求都寫入

1
2
3
4
5
6
7
8
9
// Promise.all會等全部執行完畢,才接收;其中一個失敗,就會全部失敗
Promise.all([PromiseFn(1),PromiseFn(2),PromiseFn(3)])
.then((res)=>{
console.log(res);
//這裡的res回傳的是陣列,透過res[0]、res[1]、res[2]分別取值
})
.catch((res)=>{
console.log(res);
})

Promise.all會等全部執行完畢,才接收;其中一個失敗,就會全部失敗,跑到catch

▌Promise方法:Promise.rece-最快執行完,直接跳到then

Promise.race只要其中一個執行完畢,就會停止到接收成功或失敗,其餘的請求不再執行。

1
2
3
4
5
6
7
Promise.race([PromiseFn(1),PromiseFn(2),PromiseFn(3)])
.then((res)=>{
console.log(res);
})
.catch((res)=>{
console.log(res);
})