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