Promise
- status
狀態(tài),有三種狀態(tài)pendding、resolved、rejected,狀態(tài)由 pending->resolved/rejected,不可逆
- resolve
resolve 方法,修改 promise 的狀態(tài)為 resolved,執(zhí)行 resolve 回調(diào)
- reject
reject 方法,修改 promise 的狀態(tài)為 rejected,并執(zhí)行 reject 的回調(diào)
- then
用于 promise 鏈?zhǔn)秸{(diào)用,返回一個(gè)新的 Promise 對(duì)象
常規(guī)使用方法
const p = new Promise((resolve, reject) => {
// 執(zhí)行一堆操作
resolve() // reject()
})
p.then(res => {
// 成功回調(diào)函數(shù)
}, err => {
// 失敗回調(diào)函數(shù)
})
p.then(() => {}, () => {})
// then 方法會(huì)將成功回掉函數(shù)添加到 Promise 的成功回調(diào)隊(duì)列,將失敗回調(diào)函數(shù)添加到失敗回調(diào)隊(duì)列,一個(gè) promise 對(duì)象可以調(diào)用多次 then 方法,并返回一個(gè)新的 Promise 對(duì)象,所以可以進(jìn)行鏈?zhǔn)秸{(diào)用
鏈?zhǔn)秸{(diào)用
const p1 = new Promise((resolve, reject) => {
resolve(1)
})
const p2 = new Promise((resolve, reject) => {
resolve(2)
})
p1.then(res => { // 第一次調(diào)用 then
console.log(res) // 1
return p2
}).then(res => { // 第二次調(diào)用 then
console.log(res) // 2
})
// 思考, 為什么 第二次調(diào)用 then 里面的成功回調(diào)函數(shù)的參數(shù)值會(huì)是p2的 resolve的值?
// then返回值具體規(guī)則
/*
- 如果返回一個(gè)值,則 then 返回的 Promise 狀態(tài)成為 resolved,并且返回的值作為回調(diào)的參數(shù)值
- 若沒有返回值,則狀態(tài)為 resolved,參數(shù)值為 undefined
- 若回調(diào)函數(shù)拋出錯(cuò)誤,則為 rejected,拋出的錯(cuò)誤為拒絕狀態(tài)的參數(shù)值
- 若返回 promise 對(duì)象,則狀態(tài)與該 promise 狀態(tài)一致,并且回調(diào)函數(shù)的參數(shù)值為該 promise 的狀態(tài)參數(shù)值。
*/
p1.then(res => {
return 'return value'
}).then (res => {
console.log(res) // 'return value'
}).then(res => {
console.log(res) // undefined
return p2
}).then(res => {
console.log(res) // 2
console.log(undefined.name)
}, err => {
console.log(err) //不會(huì)執(zhí)行
})
.then(res => {}, err => {
console.log(err) // TypeError: Cannot read property 'name' of undefined
return 'err'
})
.catch(err => {
console.log(err) // 不會(huì)執(zhí)行
})
.then(res => {
console.log(res) // 'err'
console.log(undefined.name)
})
.then(res => {
console.log(res) // 不會(huì)執(zhí)行
})
.catch(err => {
console.log(err) // TypeError: Cannot read property 'name' of undefined
})
// 關(guān)于promise catch 的執(zhí)行,傳遞到最近一次的 catch 方法,
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。