更新時(shí)間:2025-08-02 16:58:25作者:佚名
[id_[id_91[id_54351728]445905]113861024]
最重要貝語(yǔ)網(wǎng)校,最基本的是then
promise.then(
function(result)?{?處理一個(gè)成功的結(jié)果?},
function(error)?{?/*?handle?an?error?*/?}
);
在“then”方法中,第一個(gè)參數(shù)代表一個(gè)函數(shù),該函數(shù)會(huì)在Promise對(duì)象被成功解析后執(zhí)行,并且能夠接收到解析出的結(jié)果。
在“then”方法的第二個(gè)參數(shù)中,定義了一個(gè)函數(shù),該函數(shù)會(huì)在Promise對(duì)象被拒絕時(shí)執(zhí)行,并接收相應(yīng)的錯(cuò)誤信息。
若我們僅對(duì)實(shí)現(xiàn)目標(biāo)感興趣,那么我們便只能向.then方法傳遞一個(gè)函數(shù)作為參數(shù)。
let?promise?=?new?Promise(resolve?=>?{
setTimeout(()?=>?resolve("done!"),?1000);
});
promise.then(alert);?在經(jīng)過(guò)一秒鐘的等待后,系統(tǒng)顯示“已完成”提示。
catch
若我們專注于捕捉錯(cuò)誤,則可選擇null作為首個(gè)參數(shù)輸入,即:.then(null, errorHandlingFunction)。亦或直接采用.catch(errorHandlingFunction)這一形式,這兩種方法在功能上并無(wú)二致。
let promise = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Whoops!")), 1000);
});
捕獲異常(.catch(f))與將錯(cuò)誤處理函數(shù)(f)作為第二個(gè)參數(shù)傳遞給promise.then(null, f)的效果是相同的。
promise.catch(alert); 系統(tǒng)在1秒后顯示“錯(cuò)誤:哎呀!”的提示信息。
完全等同于對(duì).then(null, f)功能的模仿,.catch(f)僅是一種簡(jiǎn)化的表達(dá)方式。
finally方法被用于設(shè)定一個(gè)回調(diào)函數(shù),該函數(shù)將在Promise任務(wù)無(wú)論以成功(fulfilled)還是失敗(rejected)結(jié)束之后自動(dòng)執(zhí)行。通過(guò)這種方式,可以避免在then()和catch()中重復(fù)編寫(xiě)相同的代碼。
當(dāng)您需要在promise任務(wù)無(wú)論成功與否都執(zhí)行某些后續(xù)操作或進(jìn)行資源清理時(shí),可以考慮使用finally()函數(shù)。
最終,該方法的回調(diào)函數(shù)并未接收任何參數(shù),因此我們無(wú)法得知前一個(gè)Promise的狀態(tài)是成功還是失敗。
這暗示著“finally”關(guān)鍵字僅適用于那些無(wú)論最終結(jié)果如何都必須執(zhí)行的操作,它并不依賴于Promise的執(zhí)行結(jié)果。
在finally方法執(zhí)行時(shí),若未發(fā)生異常,它將直接返回原始的Promise對(duì)象值;一旦出現(xiàn)異常,則會(huì)返回包含該異常的Promise對(duì)象。概括而言,一旦Promise的狀態(tài)被設(shè)定,便無(wú)法更改,這意味著每個(gè)Promise實(shí)例在執(zhí)行完畢后,其狀態(tài)只能是resolve或reject中的一種。在執(zhí)行過(guò)程中,若遇到resolve或reject指令,后續(xù)若再遇到reject或resolve指令,則會(huì)選擇忽略該段代碼,不予執(zhí)行。盡管如此,其他部分的代碼仍將照常運(yùn)行。
var promise = new Promise((resolve, reject) => {
resolve("success1");
console.log('123');
reject("error");
console.log('456');
resolve("success2");
});
promise
.then(res => {
console.log("then: ", res);
}).catch(err => {
console.log("catch: ", err);
})
//123
//456
//then: success1
因此,在使用then、catch以及finally時(shí),它們均會(huì)生成一個(gè)新的promise對(duì)象and then是什么意思,這使得我們可以進(jìn)行鏈?zhǔn)秸{(diào)用。
在Promise機(jī)制下,任何非Promise類型的值在返回時(shí),都會(huì)被自動(dòng)封裝成一個(gè)Promise對(duì)象。
例如,當(dāng)返回字符串'hehe'時(shí),它會(huì)被轉(zhuǎn)換成返回Promise.resolve('hehe')的形式。
當(dāng)函數(shù)執(zhí)行完畢后,其返回值將僅傳遞給then函數(shù),即便其間出現(xiàn)了catch或finally塊。
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success1");
}, 1000)
});
promise
.then(res => {
console.log("then: ", res);
return 'bibi';
}).catch(err => {
console.log("catch: ", err);
return 'err';
}).finally((fin)=> {
console.log(fin);
console.log('final');
return 'haha';
}).then((res) => {
console.log(res);
console.log('final-after')
}).then((res) => {
console.log(res);
console.log('final-after2')
})
//then: success1
//undefined
//final
//bibi
//final-after
//undefined
//final-after2
catch 可以捕捉上層錯(cuò)誤,但是對(duì)下層錯(cuò)誤是捕捉不到的。
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
reject("error");
}, 1000)
});
promise
.then(res => {
console.log("then: ", res);
return 'bibi';
}).catch(err => {
console.log("catch: ", err);
return 'err'; // 這里返回了一個(gè) Promise
}).then((res)=> { // 繼續(xù)執(zhí)行
console.log('then2', res);
return Promise.reject('error2');
}).catch((err) => { //捕捉上層錯(cuò)誤,可以隔層捕捉,但是捕捉過(guò)的錯(cuò)誤不能再捕捉
console.log('catch2', err);
})
//catch: error
//then2 err
//catch2 error2
Promise對(duì)象的then或catch方法可以多次被觸發(fā),然而一旦Promise內(nèi)部的狀態(tài)發(fā)生變動(dòng)并確定了一個(gè)結(jié)果值,那么在隨后的每次調(diào)用then或catch時(shí),都會(huì)直接獲取到這個(gè)既定的值。
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('timer')
resolve('success')
}, 1000)
})
const start = Date.now();
promise.then(res => {
console.log(res, Date.now() - start)
})
promise.then(res => {
console.log(res, Date.now() - start)
})
//'timer'
//'success' 1001
//'success' 1002
Promise對(duì)象的then或catch方法可以多次被觸發(fā),然而在此場(chǎng)景中,Promise的構(gòu)造函數(shù)僅被執(zhí)行了一次。
一旦promise的內(nèi)部狀態(tài)發(fā)生變動(dòng)并賦予了一個(gè)具體數(shù)值,那么在隨后的每一次對(duì).then或.catch的調(diào)用中,都會(huì)直接接收到這個(gè)數(shù)值。
在.then或.catch方法中,若返回一個(gè)錯(cuò)誤對(duì)象,它并不會(huì)引發(fā)錯(cuò)誤and then是什么意思,因此也就不會(huì)被后續(xù)的.catch處理函數(shù)所捕捉。
Promise.resolve().then(() => {
return new Error('error!!!')
}).then(res => {
console.log("then: ", res)
}).catch(err => {
console.log("catch: ", err)
})
//"then: " "Error: error!!!"
這一結(jié)果證實(shí)了第四項(xiàng)和第六項(xiàng),表明無(wú)論返回何種非Promise類型的值,都會(huì)被自動(dòng)封裝成Promise對(duì)象。
因此,這段代碼中的return new Error('error!!!')部分也被轉(zhuǎn)化為了return Promise.resolve(new Error('error!!!'))。
當(dāng)然如果你拋出一個(gè)錯(cuò)誤的話,可以用下面的任意一種:
return Promise.reject(new Error('error!!!'));
// or
throw new Error('error!!!')
若.then或.catch方法返回的并非Promise對(duì)象,將會(huì)引發(fā)循環(huán)引用的問(wèn)題。在使用.then或.catch時(shí),預(yù)期傳入的是函數(shù)類型,若傳遞的不是函數(shù),則會(huì)直接透?jìng)髦怠?/p>
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.then(console.log)
// 1
第一個(gè)“then”中傳遞的并非函數(shù),而是數(shù)字;而第二個(gè)“then”中傳入的則是一個(gè)對(duì)象。
所以,出現(xiàn)了透?jìng)鳜F(xiàn)象,導(dǎo)致resolve(1)的數(shù)值被直接傳遞到了鏈?zhǔn)秸{(diào)用中的最后一個(gè)then函數(shù)里。
參考:/qq_38211541…