搬運學習,非原創(chuàng)
Promise 的含義
Promise
對象有以下兩個特點。
(1)對象的狀態(tài)不受外界影響去扣。Promise
對象代表一個異步操作,有三種狀態(tài):pending
(進行中)樊破、fulfilled
(已成功)和rejected
(已失斢淅狻)。只有異步操作的結(jié)果哲戚,可以決定當前是哪一種狀態(tài)奔滑,任何其他操作都無法改變這個狀態(tài)。這也是Promise
這個名字的由來顺少,它的英語意思就是“承諾”朋其,表示其他手段無法改變王浴。
(2)一旦狀態(tài)改變,就不會再變梅猿,任何時候都可以得到這個結(jié)果氓辣。Promise
對象的狀態(tài)改變,只有兩種可能:從pending
變?yōu)?code>fulfilled和從pending
變?yōu)?code>rejected袱蚓。只要這兩種情況發(fā)生钞啸,狀態(tài)就凝固了,不會再變了喇潘,會一直保持這個結(jié)果体斩,這時就稱為 resolved(已定型)。如果改變已經(jīng)發(fā)生了响蓉,你再對Promise
對象添加回調(diào)函數(shù)哨毁,也會立即得到這個結(jié)果枫甲。這與事件(Event)完全不同,事件的特點是扼褪,如果你錯過了它想幻,再去監(jiān)聽,是得不到結(jié)果的话浇。
注意脏毯,為了行文方便,本章后面的resolved
統(tǒng)一只指fulfilled
狀態(tài)幔崖,不包含rejected
狀態(tài)食店。
Promise
也有一些缺點。首先赏寇,無法取消Promise
吉嫩,一旦新建它就會立即執(zhí)行,無法中途取消嗅定。其次自娩,如果不設置回調(diào)函數(shù),Promise
內(nèi)部拋出的錯誤渠退,不會反應到外部忙迁。第三,當處于pending
狀態(tài)時碎乃,無法得知目前進展到哪一個階段(剛剛開始還是即將完成)姊扔。
如果某些事件不斷地反復發(fā)生,一般來說梅誓,使用 Stream 模式是比部署Promise
更好的選擇恰梢。
基本用法
ES6 規(guī)定晨川,Promise
對象是一個構(gòu)造函數(shù),用來生成Promise
實例删豺。
下面代碼創(chuàng)造了一個Promise
實例共虑。
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 異步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
Promise
構(gòu)造函數(shù)接受一個函數(shù)作為參數(shù),該函數(shù)的兩個參數(shù)分別是resolve
和reject
呀页。它們是兩個函數(shù)妈拌,由 JavaScript 引擎提供,不用自己部署蓬蝶。
resolve
函數(shù)的作用是尘分,將Promise
對象的狀態(tài)從“未完成”變?yōu)椤俺晒Α保磸?pending 變?yōu)?resolved),在異步操作成功時調(diào)用丸氛,并將異步操作的結(jié)果培愁,作為參數(shù)傳遞出去;reject
函數(shù)的作用是缓窜,將Promise
對象的狀態(tài)從“未完成”變?yōu)椤笆 保磸?pending 變?yōu)?rejected)定续,在異步操作失敗時調(diào)用,并將異步操作報出的錯誤禾锤,作為參數(shù)傳遞出去私股。
Promise
實例生成以后,可以用then
方法分別指定resolved
狀態(tài)和rejected
狀態(tài)的回調(diào)函數(shù)恩掷。
promise.then(function(value) {
// success
}, function(error) {
// failure
});
then
方法可以接受兩個回調(diào)函數(shù)作為參數(shù)倡鲸。第一個回調(diào)函數(shù)是Promise
對象的狀態(tài)變?yōu)?code>resolved時調(diào)用,第二個回調(diào)函數(shù)是Promise
對象的狀態(tài)變?yōu)?code>rejected時調(diào)用黄娘。其中峭状,第二個函數(shù)是可選的,不一定要提供逼争。這兩個函數(shù)都接受Promise
對象傳出的值作為參數(shù)优床。
下面是一個Promise
對象的簡單例子。
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms, 'done');
});
}
timeout(100).then((value) => {
console.log(value);
});
上面代碼中氮凝,timeout
方法返回一個Promise
實例羔巢,表示一段時間以后才會發(fā)生的結(jié)果。過了指定的時間(ms
參數(shù))以后罩阵,Promise
實例的狀態(tài)變?yōu)?code>resolved竿秆,就會觸發(fā)then
方法綁定的回調(diào)函數(shù)。
Promise 新建后就會立即執(zhí)行稿壁。
let promise = new Promise(function(resolve, reject) {
console.log('Promise');
resolve();
});
promise.then(function() {
console.log('resolved.');
});
console.log('Hi!');
// Promise
// Hi!
// resolved
上面代碼中幽钢,Promise 新建后立即執(zhí)行,所以首先輸出的是Promise
傅是。然后匪燕,then
方法指定的回調(diào)函數(shù)蕾羊,將在當前腳本所有同步任務執(zhí)行完才會執(zhí)行,所以resolved
最后輸出帽驯。
下面是異步加載圖片的例子龟再。
function loadImageAsync(url) {
return new Promise(function(resolve, reject) {
const image = new Image();
image.onload = function() {
resolve(image);
};
image.onerror = function() {
reject(new Error('Could not load image at ' + url));
};
image.src = url;
});
}
上面代碼中,使用Promise
包裝了一個圖片加載的異步操作尼变。如果加載成功利凑,就調(diào)用resolve
方法,否則就調(diào)用reject
方法嫌术。
下面是一個用Promise
對象實現(xiàn)的 Ajax 操作的例子哀澈。
const getJSON = function(url) {
const promise = new Promise(function(resolve, reject){
const handler = function() {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
});
return promise;
};
getJSON("/posts.json").then(function(json) {
console.log('Contents: ' + json);
}, function(error) {
console.error('出錯了', error);
});
上面代碼中,getJSON
是對 XMLHttpRequest 對象的封裝度气,用于發(fā)出一個針對 JSON 數(shù)據(jù)的 HTTP 請求割按,并且返回一個Promise
對象。需要注意的是磷籍,在getJSON
內(nèi)部适荣,resolve
函數(shù)和reject
函數(shù)調(diào)用時,都帶有參數(shù)择示。
如果調(diào)用resolve
函數(shù)和reject
函數(shù)時帶有參數(shù)束凑,那么它們的參數(shù)會被傳遞給回調(diào)函數(shù)。reject
函數(shù)的參數(shù)通常是Error
對象的實例栅盲,表示拋出的錯誤;resolve
函數(shù)的參數(shù)除了正常的值以外废恋,還可能是另一個 Promise 實例谈秫,比如像下面這樣。
const p1 = new Promise(function (resolve, reject) {
// ...
});
const p2 = new Promise(function (resolve, reject) {
// ...
resolve(p1);
})
上面代碼中鱼鼓,p1
和p2
都是 Promise 的實例拟烫,但是p2
的resolve
方法將p1
作為參數(shù),即一個異步操作的結(jié)果是返回另一個異步操作迄本。
注意硕淑,這時p1
的狀態(tài)就會傳遞給p2
,也就是說嘉赎,p1
的狀態(tài)決定了p2
的狀態(tài)置媳。如果p1
的狀態(tài)是pending
,那么p2
的回調(diào)函數(shù)就會等待p1
的狀態(tài)改變公条;如果p1
的狀態(tài)已經(jīng)是resolved
或者rejected
拇囊,那么p2
的回調(diào)函數(shù)將會立刻執(zhí)行。
const p1 = new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('fail')), 3000)
})
const p2 = new Promise(function (resolve, reject) {
setTimeout(() => resolve(p1), 1000)
})
p2
.then(result => console.log(result))
.catch(error => console.log(error))
// Error: fail
上面代碼中靶橱,p1
是一個 Promise寥袭,3 秒之后變?yōu)?code>rejected路捧。p2
的狀態(tài)在 1 秒之后改變,resolve
方法返回的是p1
传黄。由于p2
返回的是另一個 Promise杰扫,導致p2
自己的狀態(tài)無效了,由p1
的狀態(tài)決定p2
的狀態(tài)膘掰。所以涉波,后面的then
語句都變成針對后者(p1
)。又過了 2 秒炭序,p1
變?yōu)?code>rejected啤覆,導致觸發(fā)catch
方法指定的回調(diào)函數(shù)。
注意惭聂,調(diào)用resolve
或reject
并不會終結(jié) Promise 的參數(shù)函數(shù)的執(zhí)行窗声。
new Promise((resolve, reject) => {
resolve(1);
console.log(2);
}).then(r => {
console.log(r);
});
// 2
// 1
上面代碼中,調(diào)用resolve(1)
以后辜纲,后面的console.log(2)
還是會執(zhí)行笨觅,并且會首先打印出來。這是因為立即 resolved 的 Promise 是在本輪事件循環(huán)的末尾執(zhí)行耕腾,總是晚于本輪循環(huán)的同步任務见剩。
一般來說,調(diào)用resolve
或reject
以后扫俺,Promise 的使命就完成了苍苞,后繼操作應該放到then
方法里面,而不應該直接寫在resolve
或reject
的后面狼纬。所以羹呵,最好在它們前面加上return
語句,這樣就不會有意外疗琉。
new Promise((resolve, reject) => {
return resolve(1);
// 后面的語句不會執(zhí)行
console.log(2);
})
Promise.prototype.then()
Promise 實例具有then
方法冈欢,也就是說,then
方法是定義在原型對象Promise.prototype
上的盈简。它的作用是為 Promise 實例添加狀態(tài)改變時的回調(diào)函數(shù)凑耻。前面說過,then
方法的第一個參數(shù)是resolved
狀態(tài)的回調(diào)函數(shù)柠贤,第二個參數(shù)(可選)是rejected
狀態(tài)的回調(diào)函數(shù)香浩。
then
方法返回的是一個新的Promise
實例(注意,不是原來那個Promise
實例)种吸。因此可以采用鏈式寫法弃衍,即then
方法后面再調(diào)用另一個then
方法。
getJSON("/posts.json").then(function(json) {
return json.post;
}).then(function(post) {
// ...
});
上面的代碼使用then
方法坚俗,依次指定了兩個回調(diào)函數(shù)镜盯。第一個回調(diào)函數(shù)完成以后岸裙,會將返回結(jié)果作為參數(shù),傳入第二個回調(diào)函數(shù)速缆。
采用鏈式的then
降允,可以指定一組按照次序調(diào)用的回調(diào)函數(shù)。這時艺糜,前一個回調(diào)函數(shù)剧董,有可能返回的還是一個Promise
對象(即有異步操作),這時后一個回調(diào)函數(shù)破停,就會等待該Promise
對象的狀態(tài)發(fā)生變化翅楼,才會被調(diào)用。
getJSON("/post/1.json").then(function(post) {
return getJSON(post.commentURL);
}).then(function (comments) {
console.log("resolved: ", comments);
}, function (err){
console.log("rejected: ", err);
});
上面代碼中真慢,第一個then
方法指定的回調(diào)函數(shù)毅臊,返回的是另一個Promise
對象。這時黑界,第二個then
方法指定的回調(diào)函數(shù)管嬉,就會等待這個新的Promise
對象狀態(tài)發(fā)生變化。如果變?yōu)?code>resolved朗鸠,就調(diào)用第一個回調(diào)函數(shù)蚯撩,如果狀態(tài)變?yōu)?code>rejected,就調(diào)用第二個回調(diào)函數(shù)烛占。
如果采用箭頭函數(shù)胎挎,上面的代碼可以寫得更簡潔。
getJSON("/post/1.json").then(
post => getJSON(post.commentURL)
).then(
comments => console.log("resolved: ", comments),
err => console.log("rejected: ", err)
);
Promise.prototype.catch()
Promise.prototype.catch()
方法是.then(null, rejection)
或.then(undefined, rejection)
的別名扰楼,用于指定發(fā)生錯誤時的回調(diào)函數(shù)呀癣。
getJSON('/posts.json').then(function(posts) {
// ...
}).catch(function(error) {
// 處理 getJSON 和 前一個回調(diào)函數(shù)運行時發(fā)生的錯誤
console.log('發(fā)生錯誤!', error);
});
上面代碼中弦赖,getJSON()
方法返回一個 Promise 對象,如果該對象狀態(tài)變?yōu)?code>resolved浦辨,則會調(diào)用then()
方法指定的回調(diào)函數(shù)蹬竖;如果異步操作拋出錯誤,狀態(tài)就會變?yōu)?code>rejected流酬,就會調(diào)用catch()
方法指定的回調(diào)函數(shù)币厕,處理這個錯誤。另外芽腾,then()
方法指定的回調(diào)函數(shù)旦装,如果運行中拋出錯誤,也會被catch()
方法捕獲摊滔。
p.then((val) => console.log('fulfilled:', val))
.catch((err) => console.log('rejected', err));
// 等同于
p.then((val) => console.log('fulfilled:', val))
.then(null, (err) => console.log("rejected:", err));
下面是一個例子阴绢。
const promise = new Promise(function(resolve, reject) {
throw new Error('test');
});
promise.catch(function(error) {
console.log(error);
});
// Error: test
上面代碼中店乐,promise
拋出一個錯誤,就被catch()
方法指定的回調(diào)函數(shù)捕獲呻袭。注意眨八,上面的寫法與下面兩種寫法是等價的。
// 寫法一
const promise = new Promise(function(resolve, reject) {
try {
throw new Error('test');
} catch(e) {
reject(e);
}
});
promise.catch(function(error) {
console.log(error);
});
// 寫法二
const promise = new Promise(function(resolve, reject) {
reject(new Error('test'));
});
promise.catch(function(error) {
console.log(error);
});
比較上面兩種寫法左电,可以發(fā)現(xiàn)reject()
方法的作用廉侧,等同于拋出錯誤。
如果 Promise 狀態(tài)已經(jīng)變成resolved
篓足,再拋出錯誤是無效的段誊。
const promise = new Promise(function(resolve, reject) {
resolve('ok');
throw new Error('test');
});
promise
.then(function(value) { console.log(value) })
.catch(function(error) { console.log(error) });
// ok
上面代碼中,Promise 在resolve
語句后面栈拖,再拋出錯誤连舍,不會被捕獲,等于沒有拋出辱魁。因為 Promise 的狀態(tài)一旦改變烟瞧,就永久保持該狀態(tài),不會再變了染簇。
Promise 對象的錯誤具有“冒泡”性質(zhì)参滴,會一直向后傳遞,直到被捕獲為止锻弓。也就是說砾赔,錯誤總是會被下一個catch
語句捕獲。
getJSON('/post/1.json').then(function(post) {
return getJSON(post.commentURL);
}).then(function(comments) {
// some code
}).catch(function(error) {
// 處理前面三個Promise產(chǎn)生的錯誤
});
上面代碼中青灼,一共有三個 Promise 對象:一個由getJSON()
產(chǎn)生暴心,兩個由then()
產(chǎn)生。它們之中任何一個拋出的錯誤杂拨,都會被最后一個catch()
捕獲专普。
一般來說,不要在then()
方法里面定義 Reject 狀態(tài)的回調(diào)函數(shù)(即then
的第二個參數(shù))弹沽,總是使用catch
方法檀夹。
// bad
promise
.then(function(data) {
// success
}, function(err) {
// error
});
// good
promise
.then(function(data) { //cb
// success
})
.catch(function(err) {
// error
});
上面代碼中,第二種寫法要好于第一種寫法策橘,理由是第二種寫法可以捕獲前面then
方法執(zhí)行中的錯誤炸渡,也更接近同步的寫法(try/catch
)。因此丽已,建議總是使用catch()
方法蚌堵,而不使用then()
方法的第二個參數(shù)。
跟傳統(tǒng)的try/catch
代碼塊不同的是,如果沒有使用catch()
方法指定錯誤處理的回調(diào)函數(shù)吼畏,Promise 對象拋出的錯誤不會傳遞到外層代碼督赤,即不會有任何反應。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會報錯宫仗,因為x沒有聲明
resolve(x + 2);
});
};
someAsyncThing().then(function() {
console.log('everything is great');
});
setTimeout(() => { console.log(123) }, 2000);
// Uncaught (in promise) ReferenceError: x is not defined
// 123
上面代碼中阁危,someAsyncThing()
函數(shù)產(chǎn)生的 Promise 對象吵取,內(nèi)部有語法錯誤七兜。瀏覽器運行到這一行渴语,會打印出錯誤提示ReferenceError: x is not defined
,但是不會退出進程毅贮、終止腳本執(zhí)行办悟,2 秒之后還是會輸出123
。這就是說滩褥,Promise 內(nèi)部的錯誤不會影響到 Promise 外部的代碼病蛉,通俗的說法就是“Promise 會吃掉錯誤”。
這個腳本放在服務器執(zhí)行瑰煎,退出碼就是0
(即表示執(zhí)行成功)铺然。不過,Node.js 有一個unhandledRejection
事件酒甸,專門監(jiān)聽未捕獲的reject
錯誤魄健,上面的腳本會觸發(fā)這個事件的監(jiān)聽函數(shù),可以在監(jiān)聽函數(shù)里面拋出錯誤插勤。
process.on('unhandledRejection', function (err, p) {
throw err;
});
上面代碼中沽瘦,unhandledRejection
事件的監(jiān)聽函數(shù)有兩個參數(shù),第一個是錯誤對象农尖,第二個是報錯的 Promise 實例析恋,它可以用來了解發(fā)生錯誤的環(huán)境信息。
注意盛卡,Node 有計劃在未來廢除unhandledRejection
事件助隧。如果 Promise 內(nèi)部有未捕獲的錯誤,會直接終止進程滑沧,并且進程的退出碼不為 0喇颁。
再看下面的例子。
const promise = new Promise(function (resolve, reject) {
resolve('ok');
setTimeout(function () { throw new Error('test') }, 0)
});
promise.then(function (value) { console.log(value) });
// ok
// Uncaught Error: test
上面代碼中嚎货,Promise 指定在下一輪“事件循環(huán)”再拋出錯誤。到了那個時候蔫浆,Promise 的運行已經(jīng)結(jié)束了殖属,所以這個錯誤是在 Promise 函數(shù)體外拋出的,會冒泡到最外層瓦盛,成了未捕獲的錯誤洗显。
一般總是建議外潜,Promise 對象后面要跟catch()
方法,這樣可以處理 Promise 內(nèi)部發(fā)生的錯誤挠唆。catch()
方法返回的還是一個 Promise 對象处窥,因此后面還可以接著調(diào)用then()
方法。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會報錯玄组,因為x沒有聲明
resolve(x + 2);
});
};
someAsyncThing()
.catch(function(error) {
console.log('oh no', error);
})
.then(function() {
console.log('carry on');
});
// oh no [ReferenceError: x is not defined]
// carry on
上面代碼運行完catch()
方法指定的回調(diào)函數(shù)滔驾,會接著運行后面那個then()
方法指定的回調(diào)函數(shù)。如果沒有報錯俄讹,則會跳過catch()
方法哆致。
Promise.resolve()
.catch(function(error) {
console.log('oh no', error);
})
.then(function() {
console.log('carry on');
});
// carry on
上面的代碼因為沒有報錯,跳過了catch()
方法患膛,直接執(zhí)行后面的then()
方法摊阀。此時,要是then()
方法里面報錯踪蹬,就與前面的catch()
無關(guān)了胞此。
catch()
方法之中,還能再拋出錯誤跃捣。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會報錯漱牵,因為x沒有聲明
resolve(x + 2);
});
};
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log('oh no', error);
// 下面一行會報錯,因為 y 沒有聲明
y + 2;
}).then(function() {
console.log('carry on');
});
// oh no [ReferenceError: x is not defined]
上面代碼中枝缔,catch()
方法拋出一個錯誤布疙,因為后面沒有別的catch()
方法了,導致這個錯誤不會被捕獲愿卸,也不會傳遞到外層灵临。如果改寫一下,結(jié)果就不一樣了趴荸。
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log('oh no', error);
// 下面一行會報錯儒溉,因為y沒有聲明
y + 2;
}).catch(function(error) {
console.log('carry on', error);
});
// oh no [ReferenceError: x is not defined]
// carry on [ReferenceError: y is not defined]
上面代碼中,第二個catch()
方法用來捕獲前一個catch()
方法拋出的錯誤发钝。
Promise.prototype.finally()
finally()
方法用于指定不管 Promise 對象最后狀態(tài)如何顿涣,都會執(zhí)行的操作。該方法是 ES2018 引入標準的酝豪。
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
上面代碼中涛碑,不管promise
最后的狀態(tài),在執(zhí)行完then
或catch
指定的回調(diào)函數(shù)以后孵淘,都會執(zhí)行finally
方法指定的回調(diào)函數(shù)蒲障。
下面是一個例子,服務器使用 Promise 處理請求,然后使用finally
方法關(guān)掉服務器揉阎。
server.listen(port)
.then(function () {
// ...
})
.finally(server.stop);
finally
方法的回調(diào)函數(shù)不接受任何參數(shù)庄撮,這意味著沒有辦法知道,前面的 Promise 狀態(tài)到底是fulfilled
還是rejected
毙籽。這表明洞斯,finally
方法里面的操作,應該是與狀態(tài)無關(guān)的坑赡,不依賴于 Promise 的執(zhí)行結(jié)果烙如。
finally
本質(zhì)上是then
方法的特例。
promise
.finally(() => {
// 語句
});
// 等同于
promise
.then(
result => {
// 語句
return result;
},
error => {
// 語句
throw error;
}
);
上面代碼中垮衷,如果不使用finally
方法厅翔,同樣的語句需要為成功和失敗兩種情況各寫一次。有了finally
方法搀突,則只需要寫一次刀闷。
它的實現(xiàn)也很簡單。
Promise.prototype.finally = function (callback) {
let P = this.constructor;
return this.then(
value => P.resolve(callback()).then(() => value),
reason => P.resolve(callback()).then(() => { throw reason })
);
};
上面代碼中仰迁,不管前面的 Promise 是fulfilled
還是rejected
甸昏,都會執(zhí)行回調(diào)函數(shù)callback
。
從上面的實現(xiàn)還可以看到徐许,finally
方法總是會返回原來的值施蜜。
// resolve 的值是 undefined
Promise.resolve(2).then(() => {}, () => {})
// resolve 的值是 2
Promise.resolve(2).finally(() => {})
// reject 的值是 undefined
Promise.reject(3).then(() => {}, () => {})
// reject 的值是 3
Promise.reject(3).finally(() => {})
Promise.all()
Promise.all()
方法用于將多個 Promise 實例,包裝成一個新的 Promise 實例雌隅。
const p = Promise.all([p1, p2, p3]);
上面代碼中翻默,Promise.all()
方法接受一個數(shù)組作為參數(shù),p1
恰起、p2
修械、p3
都是 Promise 實例,如果不是检盼,就會先調(diào)用下面講到的Promise.resolve
方法肯污,將參數(shù)轉(zhuǎn)為 Promise 實例,再進一步處理吨枉。另外蹦渣,Promise.all()
方法的參數(shù)可以不是數(shù)組,但必須具有 Iterator 接口貌亭,且返回的每個成員都是 Promise 實例柬唯。
p
的狀態(tài)由p1
、p2
圃庭、p3
決定权逗,分成兩種情況美尸。
(1)只有p1
、p2
斟薇、p3
的狀態(tài)都變成fulfilled
,p
的狀態(tài)才會變成fulfilled
恕酸,此時p1
堪滨、p2
、p3
的返回值組成一個數(shù)組蕊温,傳遞給p
的回調(diào)函數(shù)袱箱。
(2)只要p1
、p2
义矛、p3
之中有一個被rejected
发笔,p
的狀態(tài)就變成rejected
,此時第一個被reject
的實例的返回值凉翻,會傳遞給p
的回調(diào)函數(shù)了讨。
下面是一個具體的例子。
// 生成一個Promise對象的數(shù)組
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){
// ...
});
上面代碼中制轰,promises
是包含 6 個 Promise 實例的數(shù)組前计,只有這 6 個實例的狀態(tài)都變成fulfilled
,或者其中有一個變?yōu)?code>rejected垃杖,才會調(diào)用Promise.all
方法后面的回調(diào)函數(shù)男杈。
下面是另一個例子。
const databasePromise = connectDatabase();
const booksPromise = databasePromise
.then(findAllBooks);
const userPromise = databasePromise
.then(getCurrentUser);
Promise.all([
booksPromise,
userPromise
])
.then(([books, user]) => pickTopRecommendations(books, user));
上面代碼中调俘,booksPromise
和userPromise
是兩個異步操作伶棒,只有等到它們的結(jié)果都返回了,才會觸發(fā)pickTopRecommendations
這個回調(diào)函數(shù)彩库。
注意肤无,如果作為參數(shù)的 Promise 實例,自己定義了catch
方法侧巨,那么它一旦被rejected
舅锄,并不會觸發(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('報錯了');
})
.then(result => result)
.catch(e => e);
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// ["hello", Error: 報錯了]
上面代碼中司忱,p1
會resolved
皇忿,p2
首先會rejected
,但是p2
有自己的catch
方法坦仍,該方法返回的是一個新的 Promise 實例鳍烁,p2
指向的實際上是這個實例。該實例執(zhí)行完catch
方法后繁扎,也會變成resolved
幔荒,導致Promise.all()
方法參數(shù)里面的兩個實例都會resolved
糊闽,因此會調(diào)用then
方法指定的回調(diào)函數(shù),而不會調(diào)用catch
方法指定的回調(diào)函數(shù)爹梁。
如果p2
沒有自己的catch
方法右犹,就會調(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('報錯了');
})
.then(result => result);
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// Error: 報錯了
Promise.race()
Promise.race()
方法同樣是將多個 Promise 實例姚垃,包裝成一個新的 Promise 實例念链。
const p = Promise.race([p1, p2, p3]);
上面代碼中,只要p1
积糯、p2
掂墓、p3
之中有一個實例率先改變狀態(tài),p
的狀態(tài)就跟著改變看成。那個率先改變的 Promise 實例的返回值君编,就傳遞給p
的回調(diào)函數(shù)。
Promise.race()
方法的參數(shù)與Promise.all()
方法一樣川慌,如果不是 Promise 實例吃嘿,就會先調(diào)用下面講到的Promise.resolve()
方法,將參數(shù)轉(zhuǎn)為 Promise 實例窘游,再進一步處理唠椭。
下面是一個例子,如果指定時間內(nèi)沒有獲得結(jié)果忍饰,就將 Promise 的狀態(tài)變?yōu)?code>reject贪嫂,否則變?yōu)?code>resolve。
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);
上面代碼中艾蓝,如果 5 秒之內(nèi)fetch
方法無法返回結(jié)果力崇,變量p
的狀態(tài)就會變?yōu)?code>rejected,從而觸發(fā)catch
方法指定的回調(diào)函數(shù)赢织。
Promise.allSettled()
Promise.allSettled()
方法接受一組 Promise 實例作為參數(shù)亮靴,包裝成一個新的 Promise 實例。只有等到所有這些參數(shù)實例都返回結(jié)果于置,不管是fulfilled
還是rejected
茧吊,包裝實例才會結(jié)束。該方法由 ES2020 引入八毯。
const promises = [
fetch('/api-1'),
fetch('/api-2'),
fetch('/api-3'),
];
await Promise.allSettled(promises);
removeLoadingIndicator();
上面代碼對服務器發(fā)出三個請求搓侄,等到三個請求都結(jié)束,不管請求成功還是失敗话速,加載的滾動圖標就會消失讶踪。
該方法返回的新的 Promise 實例,一旦結(jié)束泊交,狀態(tài)總是fulfilled
乳讥,不會變成rejected
柱查。狀態(tài)變成fulfilled
后,Promise 的監(jiān)聽函數(shù)接收到的參數(shù)是一個數(shù)組云石,每個成員對應一個傳入Promise.allSettled()
的 Promise 實例唉工。
const resolved = Promise.resolve(42);
const rejected = Promise.reject(-1);
const allSettledPromise = Promise.allSettled([resolved, rejected]);
allSettledPromise.then(function (results) {
console.log(results);
});
// [
// { status: 'fulfilled', value: 42 },
// { status: 'rejected', reason: -1 }
// ]
上面代碼中,Promise.allSettled()
的返回值allSettledPromise
留晚,狀態(tài)只可能變成fulfilled
酵紫。它的監(jiān)聽函數(shù)接收到的參數(shù)是數(shù)組results
。該數(shù)組的每個成員都是一個對象错维,對應傳入Promise.allSettled()
的兩個 Promise 實例。每個對象都有status
屬性橄唬,該屬性的值只可能是字符串fulfilled
或字符串rejected
赋焕。fulfilled
時,對象有value
屬性仰楚,rejected
時有reason
屬性隆判,對應兩種狀態(tài)的返回值。
下面是返回值用法的例子僧界。
const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];
const results = await Promise.allSettled(promises);
// 過濾出成功的請求
const successfulPromises = results.filter(p => p.status === 'fulfilled');
// 過濾出失敗的請求侨嘀,并輸出原因
const errors = results
.filter(p => p.status === 'rejected')
.map(p => p.reason);
有時候,我們不關(guān)心異步操作的結(jié)果捂襟,只關(guān)心這些操作有沒有結(jié)束咬腕。這時,Promise.allSettled()
方法就很有用葬荷。如果沒有這個方法涨共,想要確保所有操作都結(jié)束,就很麻煩宠漩。Promise.all()
方法無法做到這一點举反。
const urls = [ /* ... */ ];
const requests = urls.map(x => fetch(x));
try {
await Promise.all(requests);
console.log('所有請求都成功。');
} catch {
console.log('至少一個請求失敗扒吁,其他請求可能還沒結(jié)束火鼻。');
}
上面代碼中,Promise.all()
無法確定所有請求都結(jié)束雕崩。想要達到這個目的魁索,寫起來很麻煩,有了Promise.allSettled()
晨逝,這就很容易了蛾默。
Promise.any()
ES2021 引入了Promise.any()
方法。該方法接受一組 Promise 實例作為參數(shù)捉貌,包裝成一個新的 Promise 實例返回支鸡。只要參數(shù)實例有一個變成fulfilled
狀態(tài)冬念,包裝實例就會變成fulfilled
狀態(tài);如果所有參數(shù)實例都變成rejected
狀態(tài)牧挣,包裝實例就會變成rejected
狀態(tài)急前。
Promise.any()
跟Promise.race()
方法很像,只有一點不同瀑构,就是不會因為某個 Promise 變成rejected
狀態(tài)而結(jié)束裆针。
const promises = [
fetch('/endpoint-a').then(() => 'a'),
fetch('/endpoint-b').then(() => 'b'),
fetch('/endpoint-c').then(() => 'c'),
];
try {
const first = await Promise.any(promises);
console.log(first);
} catch (error) {
console.log(error);
}
上面代碼中,Promise.any()
方法的參數(shù)數(shù)組包含三個 Promise 操作寺晌。其中只要有一個變成fulfilled
世吨,Promise.any()
返回的 Promise 對象就變成fulfilled
。如果所有三個操作都變成rejected
呻征,那么await
命令就會拋出錯誤耘婚。
Promise.any()
拋出的錯誤,不是一個一般的錯誤陆赋,而是一個 AggregateError 實例沐祷。它相當于一個數(shù)組,每個成員對應一個被rejected
的操作所拋出的錯誤攒岛。下面是 AggregateError 的實現(xiàn)示例赖临。
new AggregateError() extends Array -> AggregateError
const err = new AggregateError();
err.push(new Error("first error"));
err.push(new Error("second error"));
throw err;
捕捉錯誤時,如果不用try...catch
結(jié)構(gòu)和 await 命令灾锯,可以像下面這樣寫兢榨。
Promise.any(promises).then(
(first) => {
// Any of the promises was fulfilled.
},
(error) => {
// All of the promises were rejected.
}
);
下面是一個例子。
var resolved = Promise.resolve(42);
var rejected = Promise.reject(-1);
var alsoRejected = Promise.reject(Infinity);
Promise.any([resolved, rejected, alsoRejected]).then(function (result) {
console.log(result); // 42
});
Promise.any([rejected, alsoRejected]).catch(function (results) {
console.log(results); // [-1, Infinity]
});
Promise.resolve()
有時需要將現(xiàn)有對象轉(zhuǎn)為 Promise 對象挠进,Promise.resolve()
方法就起到這個作用色乾。
const jsPromise = Promise.resolve($.ajax('/whatever.json'));
上面代碼將 jQuery 生成的deferred
對象,轉(zhuǎn)為一個新的 Promise 對象领突。
Promise.resolve()
等價于下面的寫法暖璧。
Promise.resolve('foo')
// 等價于
new Promise(resolve => resolve('foo'))
Promise.resolve()
方法的參數(shù)分成四種情況。
(1)參數(shù)是一個 Promise 實例
如果參數(shù)是 Promise 實例君旦,那么Promise.resolve
將不做任何修改澎办、原封不動地返回這個實例。
(2)參數(shù)是一個thenable
對象
thenable
對象指的是具有then
方法的對象金砍,比如下面這個對象局蚀。
let thenable = {
then: function(resolve, reject) {
resolve(42);
}
};
Promise.resolve()
方法會將這個對象轉(zhuǎn)為 Promise 對象,然后就立即執(zhí)行thenable
對象的then()
方法恕稠。
let thenable = {
then: function(resolve, reject) {
resolve(42);
}
};
let p1 = Promise.resolve(thenable);
p1.then(function (value) {
console.log(value); // 42
});
上面代碼中琅绅,thenable
對象的then()
方法執(zhí)行后,對象p1
的狀態(tài)就變?yōu)?code>resolved鹅巍,從而立即執(zhí)行最后那個then()
方法指定的回調(diào)函數(shù)千扶,輸出42料祠。
(3)參數(shù)不是具有then()
方法的對象,或根本就不是對象
如果參數(shù)是一個原始值澎羞,或者是一個不具有then()
方法的對象髓绽,則Promise.resolve()
方法返回一個新的 Promise 對象,狀態(tài)為resolved
妆绞。
const p = Promise.resolve('Hello');
p.then(function (s) {
console.log(s)
});
// Hello
上面代碼生成一個新的 Promise 對象的實例p
顺呕。由于字符串Hello
不屬于異步操作(判斷方法是字符串對象不具有 then 方法),返回 Promise 實例的狀態(tài)從一生成就是resolved
括饶,所以回調(diào)函數(shù)會立即執(zhí)行株茶。Promise.resolve()
方法的參數(shù),會同時傳給回調(diào)函數(shù)图焰。
(4)不帶有任何參數(shù)
Promise.resolve()
方法允許調(diào)用時不帶參數(shù)忌卤,直接返回一個resolved
狀態(tài)的 Promise 對象。
所以楞泼,如果希望得到一個 Promise 對象,比較方便的方法就是直接調(diào)用Promise.resolve()
方法笤闯。
const p = Promise.resolve();
p.then(function () {
// ...
});
上面代碼的變量p
就是一個 Promise 對象堕阔。
需要注意的是,立即resolve()
的 Promise 對象颗味,是在本輪“事件循環(huán)”(event loop)的結(jié)束時執(zhí)行超陆,而不是在下一輪“事件循環(huán)”的開始時。
setTimeout(function () {
console.log('three');
}, 0);
Promise.resolve().then(function () {
console.log('two');
});
console.log('one');
// one
// two
// three
上面代碼中浦马,setTimeout(fn, 0)
在下一輪“事件循環(huán)”開始時執(zhí)行时呀,Promise.resolve()
在本輪“事件循環(huán)”結(jié)束時執(zhí)行,console.log('one')
則是立即執(zhí)行晶默,因此最先輸出谨娜。
Promise.reject()
Promise.reject(reason)
方法也會返回一個新的 Promise 實例,該實例的狀態(tài)為rejected
磺陡。
const p = Promise.reject('出錯了');
// 等同于
const p = new Promise((resolve, reject) => reject('出錯了'))
p.then(null, function (s) {
console.log(s)
});
// 出錯了
上面代碼生成一個 Promise 對象的實例p
趴梢,狀態(tài)為rejected
,回調(diào)函數(shù)會立即執(zhí)行币他。
Promise.reject()
方法的參數(shù)坞靶,會原封不動地作為reject
的理由,變成后續(xù)方法的參數(shù)蝴悉。
Promise.reject('出錯了')
.catch(e => {
console.log(e === '出錯了')
})
// true
上面代碼中彰阴,Promise.reject()
方法的參數(shù)是一個字符串,后面catch()
方法的參數(shù)e
就是這個字符串拍冠。
應用
加載圖片
我們可以將圖片的加載寫成一個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;
});
};
Generator 函數(shù)與 Promise 的結(jié)合
使用 Generator 函數(shù)管理流程妻味,遇到異步操作的時候正压,通常返回一個Promise
對象。
function getFoo () {
return new Promise(function (resolve, reject){
resolve('foo');
});
}
const g = function* () {
try {
const foo = yield getFoo();
console.log(foo);
} catch (e) {
console.log(e);
}
};
function run (generator) {
const it = generator();
function go(result) {
if (result.done) return result.value;
return result.value.then(function (value) {
return go(it.next(value));
}, function (error) {
return go(it.throw(error));
});
}
go(it.next());
}
run(g);
上面代碼的 Generator 函數(shù)g
之中责球,有一個異步操作getFoo
焦履,它返回的就是一個Promise
對象。函數(shù)run
用來處理這個Promise
對象雏逾,并調(diào)用下一個next
方法嘉裤。
Promise.try()
實際開發(fā)中,經(jīng)常遇到一種情況:不知道或者不想?yún)^(qū)分栖博,函數(shù)f
是同步函數(shù)還是異步操作屑宠,但是想用 Promise 來處理它。因為這樣就可以不管f
是否包含異步操作仇让,都用then
方法指定下一步流程典奉,用catch
方法處理f
拋出的錯誤。一般就會采用下面的寫法丧叽。
Promise.resolve().then(f)
上面的寫法有一個缺點卫玖,就是如果f
是同步函數(shù),那么它會在本輪事件循環(huán)的末尾執(zhí)行踊淳。
const f = () => console.log('now');
Promise.resolve().then(f);
console.log('next');
// next
// now
上面代碼中假瞬,函數(shù)f
是同步的,但是用 Promise 包裝了以后迂尝,就變成異步執(zhí)行了脱茉。
那么有沒有一種方法,讓同步函數(shù)同步執(zhí)行垄开,異步函數(shù)異步執(zhí)行琴许,并且讓它們具有統(tǒng)一的 API 呢?回答是可以的说榆,并且還有兩種寫法虚吟。第一種寫法是用async
函數(shù)來寫。
const f = () => console.log('now');
(async () => f())();
console.log('next');
// now
// next
上面代碼中签财,第二行是一個立即執(zhí)行的匿名函數(shù)串慰,會立即執(zhí)行里面的async
函數(shù),因此如果f
是同步的唱蒸,就會得到同步的結(jié)果邦鲫;如果f
是異步的,就可以用then
指定下一步,就像下面的寫法庆捺。
(async () => f())()
.then(...)
需要注意的是古今,async () => f()
會吃掉f()
拋出的錯誤。所以滔以,如果想捕獲錯誤捉腥,要使用promise.catch
方法。
(async () => f())()
.then(...)
.catch(...)
第二種寫法是使用new Promise()
你画。
const f = () => console.log('now');
(
() => new Promise(
resolve => resolve(f())
)
)();
console.log('next');
// now
// next
上面代碼也是使用立即執(zhí)行的匿名函數(shù)抵碟,執(zhí)行new Promise()
。這種情況下坏匪,同步函數(shù)也是同步執(zhí)行的拟逮。
鑒于這是一個很常見的需求,所以現(xiàn)在有一個提案适滓,提供Promise.try
方法替代上面的寫法敦迄。
const f = () => console.log('now');
Promise.try(f);
console.log('next');
// now
// next
事實上,Promise.try
存在已久凭迹,Promise 庫Bluebird
罚屋、Q
和when
,早就提供了這個方法嗅绸。
由于Promise.try
為所有操作提供了統(tǒng)一的處理機制沿后,所以如果想用then
方法管理流程,最好都用Promise.try
包裝一下朽砰。這樣有許多好處,其中一點就是可以更好地管理異常喉刘。
function getUsername(userId) {
return database.users.get({id: userId})
.then(function(user) {
return user.name;
});
}
上面代碼中瞧柔,database.users.get()
返回一個 Promise 對象,如果拋出異步錯誤睦裳,可以用catch
方法捕獲造锅,就像下面這樣寫。
database.users.get({id: userId})
.then(...)
.catch(...)
但是database.users.get()
可能還會拋出同步錯誤(比如數(shù)據(jù)庫連接錯誤廉邑,具體要看實現(xiàn)方法)哥蔚,這時你就不得不用try...catch
去捕獲。
try {
database.users.get({id: userId})
.then(...)
.catch(...)
} catch (e) {
// ...
}
上面這樣的寫法就很笨拙了蛛蒙,這時就可以統(tǒng)一用promise.catch()
捕獲所有同步和異步的錯誤糙箍。
Promise.try(() => database.users.get({id: userId}))
.then(...)
.catch(...)
事實上,Promise.try
就是模擬try
代碼塊牵祟,就像promise.catch
模擬的是catch
代碼塊郑象。