1.Promise定義
(1)Promise是用來封裝一個異步操作并可以獲取其結(jié)果的構(gòu)造函數(shù);
(2)Promise是異步編程的解決方案,里面保存著未來才會結(jié)束的事件的結(jié)果;
(3)Promise有3中狀態(tài):pending:初始化狀態(tài);fullfilled:成功狀態(tài);rejected:失敗狀態(tài);
2.用法
Promise的構(gòu)造函數(shù)接收一個參數(shù),是函數(shù),并且傳入兩個參數(shù):resolve,reject,分別表示異步操作執(zhí)行成功后的回調(diào)函數(shù)和異步操作執(zhí)行失敗后的回調(diào)函數(shù)。
function test(){
var p = new Promise(function (resolve, reject) {
//做一些異步操作
setTimeout(function(){
console.log('執(zhí)行完成')
resolve('數(shù)據(jù)')
},2000)
}
return p;
}
test().then(function(data){
console.log(data)//data就是resolve中傳過來的數(shù)據(jù)
})
3.Promise.then()
在then()方法中,可以接受兩個函數(shù)參數(shù),第一個value,第二個reason。
如果拋出異常: 新promise變?yōu)閞ejected,reason為拋出的異常如果返回的是非promise的任意值,新promise變?yōu)閞esolved,value為返回的值如果返回的是另一個新promise,此promise的結(jié)果就會成為新promise的結(jié)果
new Promise((resolve, reject) => {
resolve(1)
//reject(2)
}).then(
value => {
console.log('onResolved', value)
},
reason => {
console.log('onRejected', reason)
}
)
在then()方法中,可以直接return數(shù)據(jù),也可以是Promise對象,如果是直接返回數(shù)據(jù),那么在后面的then中就可以接收數(shù)據(jù)
test().then(function(data){
console.log(data)
return test1()
}).then(function(data){
console.log(data)
return '直接返回數(shù)據(jù)'
}).then(function(data){
console.log(data)//打印“直接返回數(shù)據(jù)”
})
catch用法
對拋出的異常進行處理
test().then(function(data){
console.log('resolved')
})
.catch(function(reason){
consolve.log(reason)
})
all用法
all方法提供了并行執(zhí)行異步操作的能力,并且在所有異步操作執(zhí)行完后才執(zhí)行回調(diào)。all接收一個數(shù)組參數(shù),里面的值最終都是返回promise對象。當數(shù)組中的所有promise都為resolve時才成功,有reject回調(diào)執(zhí)行或輸入不合法的promise就會立即拋出錯誤。
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
race用法
race 函數(shù)返回一個 Promise,它將與第一個傳遞的 promise 相同的完成方式被完成(參數(shù)中第一個執(zhí)行完的promise的返回狀態(tài)就是race的返回狀態(tài))。它可以是完成( resolves),也可以是失?。╮ejects),這要取決于第一個完成的方式是兩個中的哪個。
例如:進行圖片的請求
//請求某個圖片資源
function requestImg(){
var p = new Promise(function(resolve, reject){
var img = new Image();
img.onload = function(){
resolve(img);
}
img.src = 'xxxxxx';
});
return p;
}
//延時函數(shù),用于給請求計時
function timeout(){
var p = new Promise(function(resolve, reject){
setTimeout(function(){
reject('圖片請求超時');
}, 5000);
});
return p;
}
Promise
.race([requestImg(), timeout()])
.then(function(results){
console.log(results);
})
.catch(function(reason){
console.log(reason);
});
requestImg()請求圖片肯定不會成功,timeout函數(shù)是一個延時5秒的異步操作。當兩個返回promise對象的函數(shù)放進race中,它倆就會賽跑,5秒內(nèi)圖片成功請求,那就進入then方法,執(zhí)行正常流程,5秒內(nèi)不成功,進入timeout中執(zhí)行。