1.調(diào)用resolve或reject并不會終結(jié) Promise 的參數(shù)函數(shù)的執(zhí)行鉴逞;
new Promise((resolve, reject) => {
resolve(1);
reject(2);
console.log(2);
}).then(r => {
console.log(r);
});
// 2 console.log(2)會在resolve/reject之后繼續(xù)執(zhí)行恶耽,但是reject不會在resolve之后執(zhí)行蛹含;
// 1
2.在race,all,allSettled方法中衅鹿,如果拋錯(cuò)的Promise自己有catch撒踪,狀態(tài)則也是fulfilled;
3.待續(xù)...
基本用法
異步請求數(shù)據(jù):
getCategory(){
let temp = true;
return new Promise((resolve,reject)=>{
if(temp){
resolve('成功數(shù)據(jù)')
// 更優(yōu)寫法:return resolve('成功數(shù)據(jù)')
}else {
//拋錯(cuò)方式1
reject('err信息')
reject(new Error('err信息'))
//拋錯(cuò)方式2
throw new Error('err信息')
}
},
請求數(shù)據(jù)之后:
this.getCategory().then(
(res)=>{console.log(res)}
//接收錯(cuò)誤方式1
(err)=>{console.log(err)}
)
//接收錯(cuò)誤方式2 --建議使用此種方式大渤,這種方式不僅能獲取promise中的錯(cuò)誤制妄,還能獲取到then方法中的;
this.getCategory()
.then()
.catch(err=>{
console.log(err)
})
如果有多個(gè)then()的情況泵三,前一個(gè)回調(diào)函數(shù)返回的是一個(gè)Promise對象(即有異步操作)耕捞,
后一個(gè)回調(diào)函數(shù),就會等待前一個(gè)then執(zhí)行完畢烫幕,才會被調(diào)用俺抽。
.finally(() => {···})
不管 Promise 對象最后狀態(tài)如何,都會執(zhí)行的操作较曼,finally本質(zhì)上是then方法的特例磷斧;
finally回調(diào)不接收參數(shù);
promise.all基本用法:都成功的時(shí)候才得到(有catch回調(diào)例外)
const p1 = new Promise((resolve, reject) => {
resolve('hello');
}).catch(e => e);
const p2 = new Promise((resolve, reject) => {
resolve('world');
}).catch(e => e);
Promise.all([p1, p2])
.then(result => {
console.log(result) //['hello','world']
})
.catch(e => console.log(e))
//then接收數(shù)組的另一種方式如下:
// .then(([r1,r2]) => {
// console.log(r1) //hello
// console.log(r2) //world
// })
promise.race基本用法:誰先返回得到誰捷犹,如果先的那個(gè)拋錯(cuò)則結(jié)束
const p1 = new Promise((resolve, reject) => {
resolve('hello');
}).catch(e => e);
const p2 = new Promise((resolve, reject) => {
resolve('world');
}).catch(e => e);
Promise.race([p1, p2])
.then(result => {
console.log(result) //hello
})
.catch(e => console.log(e))
Promise.allSettled 基本用法:只關(guān)心操作是否結(jié)束弛饭,并且可以得到多個(gè)請求中的所有正確的請求;
const p1 = new Promise((resolve, reject) => {
resolve('hello');
}).catch(e => e);
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('world');
}, 3000)
}).catch(e => e);
const p3 = new Promise((resolve, reject) => {
resolve('hihihi');
}).catch(e => e);
基本用法:
Promise.allSettled([p1,p2,p3])
.then(results=>{
console.log(results)
//一個(gè)對象數(shù)組伏恐,包含每個(gè)promise得到的對象孩哑,正確的是status+value,錯(cuò)誤的是status+reason(reason.message才能得到錯(cuò)誤信息)
})
項(xiàng)目使用方式:
async function getSomething() {
const results = await Promise.allSettled([p1,p2,p3]);
console.log('所有請求都執(zhí)行完之后再做點(diǎn)兒啥')
// 過濾出成功的請求
const successfulPromises = results.filter(p => p.status === 'fulfilled');
// 過濾出失敗的請求栓霜,并輸出原因
const errors = results
.filter(p => p.status === 'rejected')
.map(p => p.reason);
}
getSomething()
Promise.any() 基本用法:數(shù)實(shí)例有一個(gè)變成fulfilled狀態(tài)翠桦,包裝實(shí)例就會變成fulfilled狀態(tài);如果所有參數(shù)實(shí)例都變成rejected狀態(tài),包裝實(shí)例就會變成rejected狀態(tài)销凑,不像race一個(gè)rejected則會直接中斷丛晌;
注意:該方法目前是一個(gè)第三階段的提案,還不能正式使用斗幼。