-
Promise
是異步編程的一種解決方案,它相當(dāng)于一個(gè)容器减牺,里面保存著未來(lái)才會(huì)結(jié)束的事件笼才,它也主要是用來(lái)解決回調(diào)地獄的問(wèn)題溢谤。
-
promise
是一個(gè)對(duì)象斩松,代表一個(gè)異步操作伶唯,有三種狀態(tài),進(jìn)行中惧盹,成功乳幸,失敗。只有異步操作的結(jié)果的可以決定當(dāng)前是哪種狀態(tài)钧椰,promise
一旦新建執(zhí)行粹断,就沒(méi)有辦法中途停止。
-
promise
允許函數(shù)作為參數(shù)傳入嫡霞,res
為成功的回調(diào)瓶埋,rej
為失敗的回調(diào),當(dāng)條件滿足時(shí)诊沪,res/rej
會(huì)將成功或失敗的結(jié)果暴露出來(lái)养筒。
- 通過(guò)
.then
拿到暴露出來(lái)的結(jié)果,.then
是一個(gè)全新的promise
函數(shù)端姚,.then
允許兩個(gè)函數(shù)作為參數(shù)晕粪,一個(gè)函數(shù)拿到成功的暴露結(jié)果,一個(gè)拿失敗暴露的結(jié)果渐裸。
- 通過(guò)
catch
獲取一個(gè)指定發(fā)生錯(cuò)誤時(shí)的回調(diào)函數(shù)巫湘。error
為錯(cuò)誤信息装悲。
- 一般來(lái)說(shuō),不要在
then
方法里面定義 rej
狀態(tài)的回調(diào)函數(shù)(即then的第二個(gè)參數(shù))剩膘,總是使用catch
方法衅斩。
const pro=new Promise((res,rej)=>{
if(!true){
res('123')
}
else{
rej("4576")
}
}).then((res)=>{
console.log(res)
},(rej)=>{
console.log(rej)
}).catch((error)=>{
console.log(error)
}
)
-
Promise.all
方法用于將多個(gè)Promise
實(shí)例,包裝成一個(gè)新的Promise
實(shí)例怠褐。只有當(dāng)作為參數(shù)所有的promise
函數(shù)運(yùn)行完畢畏梆,才會(huì)執(zhí)行.then
回調(diào)。
- 如果作為參數(shù)的 Promise 實(shí)例奈懒,自己定義了catch方法奠涌,那么它一旦被出錯(cuò),并不會(huì)觸發(fā)Promise.all()的catch方法磷杏。
const promises = [2, 3, 5, 7, 11, 13].map(function (id) {
return getJSON('/post/' + id + ".json");
});
Promise.all(promises).then(function (posts) {
// ...
}).catch(function(reason){
// ...
});
- Promise.race()法用于將多個(gè)
Promise
實(shí)例溜畅,包裝成一個(gè)新的Promise
實(shí)例。只有當(dāng)作為參數(shù)所有的promise
函數(shù)有一個(gè)運(yùn)行完畢极祸,就會(huì)執(zhí)行.then
回調(diào)慈格。
const promises = [2, 3, 5, 7, 11, 13].map(function (id) {
return getJSON('/post/' + id + ".json");
});
Promise.race(promises).then(function (posts) {
// ...
}).catch(function(reason){
// ...
});
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者