一、介紹
Promise,譯為承諾,是異步編程的一種解決方案,比傳統(tǒng)的解決方案(回調(diào)函數(shù))更加合理和更加強(qiáng)大
在以往我們?nèi)绻幚矶鄬赢惒讲僮鳎覀兺鶗?huì)像下面那樣編寫我們的代碼
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('得到最終結(jié)果: ' + finalResult);
}, failureCallback);
}, failureCallback);
}, failureCallback);
閱讀上面代碼,是不是很難受,上述形成了經(jīng)典的回調(diào)地獄
現(xiàn)在通過Promise的改寫上面的代碼
doSomething().then(function(result) {
return doSomethingElse(result);
})
.then(function(newResult) {
return doThirdThing(newResult);
})
.then(function(finalResult) {
console.log('得到最終結(jié)果: ' + finalResult);
})
.catch(failureCallback);
瞬間感受到promise解決異步操作的優(yōu)點(diǎn):
- 鏈?zhǔn)讲僮鳒p低了編碼難度
- 代碼可讀性明顯增強(qiáng)
下面我們正式來認(rèn)識(shí)promise:
狀態(tài)
promise對(duì)象僅有三種狀態(tài)
- pending(進(jìn)行中)
- fulfilled(已成功)
- rejected(已失?。?/li>
特點(diǎn)
- 對(duì)象的狀態(tài)不受外界影響,只有異步操作的結(jié)果,可以決定當(dāng)前是哪一種狀態(tài)
- 一旦狀態(tài)改變(從pending變?yōu)閒ulfilled和從pending變?yōu)閞ejected),就不會(huì)再變,任何時(shí)候都可以得到這個(gè)結(jié)果
流程
認(rèn)真閱讀下圖,我們能夠輕松了解promise整個(gè)流程
二、用法
Promise對(duì)象是一個(gè)構(gòu)造函數(shù),用來生成Promise實(shí)例
const promise = new Promise(function(resolve, reject) {});
Promise構(gòu)造函數(shù)接受一個(gè)函數(shù)作為參數(shù),該函數(shù)的兩個(gè)參數(shù)分別是resolve和reject
- resolve函數(shù)的作用是,將Promise對(duì)象的狀態(tài)從“未完成”變?yōu)椤俺晒Α?/li>
- reject函數(shù)的作用是,將Promise對(duì)象的狀態(tài)從“未完成”變?yōu)椤笆 ?/li>
實(shí)例方法
Promise構(gòu)建出來的實(shí)例存在以下方法:
- then()
- catch()
- finally()
then()
then是實(shí)例狀態(tài)發(fā)生改變時(shí)的回調(diào)函數(shù),第一個(gè)參數(shù)是resolved狀態(tài)的回調(diào)函數(shù),第二個(gè)參數(shù)是rejected狀態(tài)的回調(diào)函數(shù)
then方法返回的是一個(gè)新的Promise實(shí)例,也就是promise能鏈?zhǔn)綍鴮懙脑?/p>
getJSON("/posts.json").then(function(json) {
return json.post;
}).then(function(post) {
// ...
});
catch
catch()方法是.then(null, rejection)或.then(undefined, rejection)的別名,用于指定發(fā)生錯(cuò)誤時(shí)的回調(diào)函數(shù)
getJSON('/posts.json').then(function(posts) {
// ...
}).catch(function(error) {
// 處理 getJSON 和 前一個(gè)回調(diào)函數(shù)運(yùn)行時(shí)發(fā)生的錯(cuò)誤
console.log('發(fā)生錯(cuò)誤!', error);
});
Promise對(duì)象的錯(cuò)誤具有“冒泡”性質(zhì),會(huì)一直向后傳遞,直到被捕獲為止
getJSON('/post/1.json').then(function(post) {
return getJSON(post.commentURL);
}).then(function(comments) {
// some code
}).catch(function(error) {
// 處理前面三個(gè)Promise產(chǎn)生的錯(cuò)誤
});
一般來說,使用catch方法代替then()第二個(gè)參數(shù)
Promise對(duì)象拋出的錯(cuò)誤不會(huì)傳遞到外層代碼,即不會(huì)有任何反應(yīng)
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會(huì)報(bào)錯(cuò),因?yàn)閤沒有聲明
resolve(x + 2);
});
};
瀏覽器運(yùn)行到這一行,會(huì)打印出錯(cuò)誤提示ReferenceError: x is not defined,但是不會(huì)退出進(jìn)程
catch()方法之中,還能再拋出錯(cuò)誤,通過后面catch方法捕獲到
finally()
finally()方法用于指定不管 Promise 對(duì)象最后狀態(tài)如何,都會(huì)執(zhí)行的操作
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
構(gòu)造函數(shù)方法
Promise構(gòu)造函數(shù)存在以下方法:
- all()
- race()
- allSettled()
- resolve()
- reject()
- try()
all()
Promise.all()方法用于將多個(gè) Promise實(shí)例,包裝成一個(gè)新的 Promise實(shí)例
const p = Promise.all([p1, p2, p3]);
接受一個(gè)數(shù)組(迭代對(duì)象)作為參數(shù),數(shù)組成員都應(yīng)為Promise實(shí)例
實(shí)例p的狀態(tài)由p1、p2、p3決定,分為兩種:
- 只有p1、p2、p3的狀態(tài)都變成fulfilled,p的狀態(tài)才會(huì)變成fulfilled,此時(shí)p1、p2、p3的返回值組成一個(gè)數(shù)組,傳遞給p的回調(diào)函數(shù)
- 只要p1、p2、p3之中有一個(gè)被rejected,p的狀態(tài)就變成rejected,此時(shí)第一個(gè)被reject的實(shí)例的返回值,會(huì)傳遞給p的回調(diào)函數(shù)
注意,如果作為參數(shù)的 Promise 實(shí)例,自己定義了catch方法,那么它一旦被rejected,并不會(huì)觸發(fā)Promise.all()的catch方法
const p1 = new Promise((resolve, reject) => {
resolve('hello');
})
.then(result => result)
.catch(e => e);
const p2 = new Promise((resolve, reject) => {
throw new Error('報(bào)錯(cuò)了');
})
.then(result => result)
.catch(e => e);
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// ["hello", Error: 報(bào)錯(cuò)了]
如果p2沒有自己的catch方法,就會(huì)調(diào)用Promise.all()的catch方法
const p1 = new Promise((resolve, reject) => {
resolve('hello');
})
.then(result => result);
const p2 = new Promise((resolve, reject) => {
throw new Error('報(bào)錯(cuò)了');
})
.then(result => result);
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// Error: 報(bào)錯(cuò)了
race()
Promise.race()方法同樣是將多個(gè) Promise 實(shí)例,包裝成一個(gè)新的 Promise 實(shí)例
const p = Promise.race([p1, p2, p3]);
只要p1、p2、p3之中有一個(gè)實(shí)例率先改變狀態(tài),p的狀態(tài)就跟著改變
率先改變的 Promise 實(shí)例的返回值則傳遞給p的回調(diào)函數(shù)
const p = Promise.race([
fetch('/resource-that-may-take-a-while'),
new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('request timeout')), 5000)
})
]);
p
.then(console.log)
.catch(console.error);
allSettled()
Promise.allSettled()方法接受一組 Promise 實(shí)例作為參數(shù),包裝成一個(gè)新的 Promise 實(shí)例
只有等到所有這些參數(shù)實(shí)例都返回結(jié)果,不管是fulfilled還是rejected,包裝實(shí)例才會(huì)結(jié)束
const promises = [
fetch('/api-1'),
fetch('/api-2'),
fetch('/api-3'),
];
await Promise.allSettled(promises);
removeLoadingIndicator();
resolve()
將現(xiàn)有對(duì)象轉(zhuǎn)為 Promise對(duì)象
Promise.resolve(‘foo’)
// 等價(jià)于
new Promise(resolve => resolve(‘foo’))
參數(shù)可以分成四種情況,分別如下:
- 參數(shù)是一個(gè) Promise 實(shí)例,promise.resolve將不做任何修改、原封不動(dòng)地返回這個(gè)實(shí)例
- 參數(shù)是一個(gè)thenable對(duì)象,promise.resolve會(huì)將這個(gè)對(duì)象轉(zhuǎn)為 Promise對(duì)象,然后就立即執(zhí)行thenable對(duì)象的then()方法
- 參數(shù)不是具有then()方法的對(duì)象,或根本就不是對(duì)象,Promise.resolve()會(huì)返回一個(gè)新的 Promise 對(duì)象,狀態(tài)為resolved
- 沒有參數(shù)時(shí),直接返回一個(gè)resolved狀態(tài)的 Promise 對(duì)象
reject()
Promise.reject(reason)方法也會(huì)返回一個(gè)新的 Promise 實(shí)例,該實(shí)例的狀態(tài)為rejected
const p = Promise.reject('出錯(cuò)了');
// 等同于
const p = new Promise((resolve, reject) => reject('出錯(cuò)了'))
p.then(null, function (s) {
console.log(s)
});
// 出錯(cuò)了
Promise.reject()方法的參數(shù),會(huì)原封不動(dòng)地變成后續(xù)方法的參數(shù)
Promise.reject('出錯(cuò)了')
.catch(e => {
console.log(e === '出錯(cuò)了')
})
// true
三、使用場(chǎng)景
將圖片的加載寫成一個(gè)Promise,一旦加載完成,Promise的狀態(tài)就發(fā)生變化
const preloadImage = function (path) {
return new Promise(function (resolve, reject) {
const image = new Image();
image.onload = resolve;
image.onerror = reject;
image.src = path;
});
};
通過鏈?zhǔn)讲僮?,將多個(gè)渲染數(shù)據(jù)分別給個(gè)then,讓其各司其職。或當(dāng)下個(gè)異步請(qǐng)求依賴上個(gè)請(qǐng)求結(jié)果的時(shí)候,我們也能夠通過鏈?zhǔn)讲僮饔押媒鉀Q問題
// 各司其職
getInfo().then(res=>{
let { bannerList } = res
//渲染輪播圖
console.log(bannerList)
return res
}).then(res=>{
let { storeList } = res
//渲染店鋪列表
console.log(storeList)
return res
}).then(res=>{
let { categoryList } = res
console.log(categoryList)
//渲染分類列表
return res
})
通過all()實(shí)現(xiàn)多個(gè)請(qǐng)求合并在一起,匯總所有請(qǐng)求結(jié)果,只需設(shè)置一個(gè)loading即可文章來源:http://www.zghlxwxcb.cn/news/detail-610015.html
function initLoad(){
// loading.show() //加載loading
Promise.all([getBannerList(),getStoreList(),getCategoryList()]).then(res=>{
console.log(res)
loading.hide() //關(guān)閉loading
}).catch(err=>{
console.log(err)
loading.hide()//關(guān)閉loading
})
}
//數(shù)據(jù)初始化
initLoad()
通過race可以設(shè)置圖片請(qǐng)求超時(shí)文章來源地址http://www.zghlxwxcb.cn/news/detail-610015.html
//請(qǐng)求某個(gè)圖片資源
function requestImg(){
var p = new Promise(function(resolve, reject){
var img = new Image();
img.onload = function(){
resolve(img);
}
//img.src = "https://b-gold-cdn.xitu.io/v3/static/img/logo.a7995ad.svg"; 正確的
img.src = "https://b-gold-cdn.xitu.io/v3/static/img/logo.a7995ad.svg1";
});
return p;
}
//延時(shí)函數(shù),用于給請(qǐng)求計(jì)時(shí)
function timeout(){
var p = new Promise(function(resolve, reject){
setTimeout(function(){
reject('圖片請(qǐng)求超時(shí)');
}, 5000);
});
return p;
}
Promise
.race([requestImg(), timeout()])
.then(function(results){
console.log(results);
})
.catch(function(reason){
console.log(reason);
});
到了這里,關(guān)于ES6基礎(chǔ)知識(shí)六:你是怎么理解ES6中 Promise的?使用場(chǎng)景?的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!