Promise 的含義
Promise 是異步編程的一種解決方案,所謂Promise,簡(jiǎn)單說(shuō)就是一個(gè)容器瑰谜,里面保存著某個(gè)未來(lái)才會(huì)
結(jié)束的事件(通常是一個(gè)異步操作)的結(jié)果。從語(yǔ)法上說(shuō)树绩,Promise 是一個(gè)對(duì)象萨脑,從它可以獲取異步
操作的消息。Promise 提供統(tǒng)一的 API饺饭,各種異步操作都可以用同樣的方法進(jìn)行處理渤早。
Promise對(duì)象有以下兩個(gè)特點(diǎn) :
(1)對(duì)象的狀態(tài)不受外界影響。Promise對(duì)象代表一個(gè)異步操作瘫俊,有三種狀態(tài):pending(進(jìn)行中)鹊杖、fulfilled(已成功)和rejected(已失敗)扛芽。只有異步操作的結(jié)果骂蓖,可以決定當(dāng)前是哪一種狀態(tài),任何其他操作都無(wú)法改變這個(gè)狀態(tài)川尖。這也是Promise這個(gè)名字的由來(lái)登下,它的英語(yǔ)意思就是“承諾”,表示其他手段無(wú)法改變。
(2)一旦狀態(tài)改變庐船,就不會(huì)再變银酬,任何時(shí)候都可以得到這個(gè)結(jié)果。Promise對(duì)象的狀態(tài)改變筐钟,只有兩種可能:從pending變?yōu)閒ulfilled和從pending變?yōu)閞ejected。只要這兩種情況發(fā)生赋朦,狀態(tài)就凝固了篓冲,不會(huì)再變了,會(huì)一直保持這個(gè)結(jié)果,這時(shí)就稱為 resolved(已定型)。如果改變已經(jīng)發(fā)生了冀墨,你再對(duì)Promise對(duì)象添加回調(diào)函數(shù)彼哼,也會(huì)立即得到這個(gè)結(jié)果。這與事件(Event)完全不同敲才,事件的特點(diǎn)是,如果你錯(cuò)過(guò)了它,再去監(jiān)聽(tīng)暴区,是得不到結(jié)果的。
注意辛臊,為了行文方便仙粱,本章后面的resolved統(tǒng)一只指fulfilled狀態(tài),不包含rejected狀態(tài)彻舰。
有了Promise對(duì)象伐割,就可以將異步操作以同步操作的流程表達(dá)出來(lái),避免了層層嵌套的回調(diào)函數(shù)刃唤。此外隔心,Promise對(duì)象提供統(tǒng)一的接口,使得控制異步操作更加容易尚胞。
Promise也有一些缺點(diǎn)硬霍。首先,無(wú)法取消Promise辐真,一旦新建它就會(huì)立即執(zhí)行须尚,無(wú)法中途取消。其次侍咱,如果不設(shè)置回調(diào)函數(shù)耐床,Promise內(nèi)部拋出的錯(cuò)誤,不會(huì)反應(yīng)到外部楔脯。第三撩轰,當(dāng)處于pending狀態(tài)時(shí),無(wú)法得知目前進(jìn)展到哪一個(gè)階段(剛剛開(kāi)始還是即將完成)。
基本用法
ES6 規(guī)定堪嫂,Promise對(duì)象是一個(gè)構(gòu)造函數(shù)偎箫,用來(lái)生成Promise實(shí)例。
下面代碼創(chuàng)造了一個(gè)Promise實(shí)例皆串。
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 異步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
Promise構(gòu)造函數(shù)接受一個(gè)函數(shù)作為參數(shù)淹办,該函數(shù)的兩個(gè)參數(shù)分別是resolve和reject。它們是兩個(gè)函數(shù)恶复,由 JavaScript 引擎提供怜森,不用自己部署。
resolve函數(shù)的作用是谤牡,將Promise對(duì)象的狀態(tài)從“未完成”變?yōu)椤俺晒Α保磸?pending 變?yōu)?resolved)副硅,
在異步操作成功時(shí)調(diào)用,并將異步操作的結(jié)果翅萤,作為參數(shù)傳遞出去恐疲;reject函數(shù)的作用是,將Promise對(duì)
象的狀態(tài)從“未完成”變?yōu)椤笆 保磸?pending 變?yōu)?rejected)套么,在異步操作失敗時(shí)調(diào)用培己,并將異步
操作報(bào)出的錯(cuò)誤,作為參數(shù)傳遞出去违诗。
Promise實(shí)例生成以后漱凝,可以用then方法分別指定resolved狀態(tài)和rejected狀態(tài)的回調(diào)函數(shù)。
promise.then(function(value) {
// success
}, function(error) {
// failure
});
then方法可以接受兩個(gè)回調(diào)函數(shù)作為參數(shù)诸迟。第一個(gè)回調(diào)函數(shù)是Promise對(duì)象的狀態(tài)變?yōu)閞esolved時(shí)調(diào)用茸炒,
第二個(gè)回調(diào)函數(shù)是Promise對(duì)象的狀態(tài)變?yōu)閞ejected時(shí)調(diào)用。這兩個(gè)函數(shù)都是可選的阵苇,不一定要提供壁公。
它們都接受Promise對(duì)象傳出的值作為參數(shù)。
下面是一個(gè)Promise對(duì)象的簡(jiǎn)單例子绅项。
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms, 'done');
});
}
timeout(100).then((value) => {
console.log(value);
});
上面代碼中紊册,timeout方法返回一個(gè)Promise實(shí)例,表示一段時(shí)間以后才會(huì)發(fā)生的結(jié)果快耿。過(guò)了指定的時(shí)間(ms參數(shù))以后囊陡,Promise實(shí)例的狀態(tài)變?yōu)閞esolved,就會(huì)觸發(fā)then方法綁定的回調(diào)函數(shù)掀亥。
Promise 新建后就會(huì)立即執(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ù),將在當(dāng)前腳本所有同步任務(wù)執(zhí)行完才會(huì)執(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包裝了一個(gè)圖片加載的異步操作许师。如果加載成功,就調(diào)用resolve方法僚匆,否則就調(diào)用reject方法枯跑。
下面是一個(gè)用Promise對(duì)象實(shí)現(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('出錯(cuò)了', error);
});
上面代碼中白热,getJSON是對(duì) XMLHttpRequest 對(duì)象的封裝,用于發(fā)出一個(gè)針對(duì) JSON 數(shù)據(jù)的 HTTP 請(qǐng)求粗卜,并且返回一個(gè)Promise對(duì)象屋确。需要注意的是,在getJSON內(nèi)部续扔,resolve函數(shù)和reject函數(shù)調(diào)用時(shí)攻臀,都帶有參數(shù)。
如果調(diào)用resolve函數(shù)和reject函數(shù)時(shí)帶有參數(shù)纱昧,那么它們的參數(shù)會(huì)被傳遞給回調(diào)函數(shù)刨啸。reject函數(shù)的參數(shù)通常是Error對(duì)象的實(shí)例,表示拋出的錯(cuò)誤识脆;resolve函數(shù)的參數(shù)除了正常的值以外设联,還可能是另一個(gè) Promise 實(shí)例,比如像下面這樣灼捂。
const p1 = new Promise(function (resolve, reject) {
// ...
});
const p2 = new Promise(function (resolve, reject) {
// ...
resolve(p1);
})
上面代碼中离例,p1和p2都是 Promise 的實(shí)例,但是p2的resolve方法將p1作為參數(shù)悉稠,即一個(gè)異步操作的結(jié)果是返回另一個(gè)異步操作宫蛆。
注意,這時(shí)p1的狀態(tài)就會(huì)傳遞給p2的猛,也就是說(shuō)耀盗,p1的狀態(tài)決定了p2的狀態(tài)。如果p1的狀態(tài)是pending卦尊,那么p2的回調(diào)函數(shù)就會(huì)等待p1的狀態(tài)改變叛拷;如果p1的狀態(tài)已經(jīng)是resolved或者rejected,那么p2的回調(diào)函數(shù)將會(huì)立刻執(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是一個(gè) Promise邓线,3 秒之后變?yōu)閞ejected。p2的狀態(tài)在 1 秒之后改變煌恢,resolve方法返回的是p1骇陈。由于p2返回的是另一個(gè) Promise,導(dǎo)致p2自己的狀態(tài)無(wú)效了瑰抵,由p1的狀態(tài)決定p2的狀態(tài)你雌。所以,后面的then語(yǔ)句都變成針對(duì)后者(p1)二汛。又過(guò)了 2 秒婿崭,p1變?yōu)閞ejected,導(dǎo)致觸發(fā)catch方法指定的回調(diào)函數(shù)肴颊。
注意氓栈,調(diào)用resolve或reject并不會(huì)終結(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)還是會(huì)執(zhí)行,并且會(huì)首先打印出來(lái)竟宋。這是因?yàn)榱⒓?resolved 的 Promise 是在本輪事件循環(huán)的末尾執(zhí)行提完,總是晚于本輪循環(huán)的同步任務(wù)。
一般來(lái)說(shuō)丘侠,調(diào)用resolve或reject以后徒欣,Promise 的使命就完成了,后繼操作應(yīng)該放到then方法里面蜗字,而不應(yīng)該直接寫在resolve或reject的后面打肝。所以,最好在它們前面加上return語(yǔ)句秽澳,這樣就不會(huì)有意外闯睹。
new Promise((resolve, reject) => {
return resolve(1);
// 后面的語(yǔ)句不會(huì)執(zhí)行
console.log(2);
})
Promise.prototype.then()
Promise 實(shí)例具有then方法,也就是說(shuō)担神,then方法是定義在原型對(duì)象Promise.prototype上的楼吃。
它的作用是為 Promise 實(shí)例添加狀態(tài)改變時(shí)的回調(diào)函數(shù)。前面說(shuō)過(guò)妄讯,then方法的第一個(gè)參數(shù)是
resolved狀態(tài)的回調(diào)函數(shù)孩锡,第二個(gè)參數(shù)是rejected狀態(tài)的回調(diào)函數(shù),它們都是可選的亥贸。
then方法返回的是一個(gè)新的Promise實(shí)例(注意躬窜,不是原來(lái)那個(gè)Promise實(shí)例)。因此可以采用鏈?zhǔn)綄懛恢茫磘hen方法后面再調(diào)用另一個(gè)then方法荣挨。
getJSON("/posts.json").then(function(json) {
return json.post;
}).then(function(post) {
// ...
});
上面的代碼使用then方法男韧,依次指定了兩個(gè)回調(diào)函數(shù)。第一個(gè)回調(diào)函數(shù)完成以后默垄,會(huì)將返回結(jié)果作為參數(shù)此虑,傳入第二個(gè)回調(diào)函數(shù)。
采用鏈?zhǔn)降膖hen口锭,可以指定一組按照次序調(diào)用的回調(diào)函數(shù)朦前。這時(shí),前一個(gè)回調(diào)函數(shù)鹃操,有可能返回的還是一個(gè)Promise對(duì)象(即有異步操作)韭寸,這時(shí)后一個(gè)回調(diào)函數(shù),就會(huì)等待該P(yáng)romise對(duì)象的狀態(tài)發(fā)生變化荆隘,才會(huì)被調(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);
});
上面代碼中,第一個(gè)then方法指定的回調(diào)函數(shù)椰拒,返回的是另一個(gè)Promise對(duì)象莫其。這時(shí),第二個(gè)then方法指定的回調(diào)函數(shù)耸三,就會(huì)等待這個(gè)新的Promise對(duì)象狀態(tài)發(fā)生變化。如果變?yōu)閞esolved浇揩,就調(diào)用第一個(gè)回調(diào)函數(shù)仪壮,如果狀態(tài)變?yōu)閞ejected,就調(diào)用第二個(gè)回調(diào)函數(shù)胳徽。
如果采用箭頭函數(shù)积锅,上面的代碼可以寫得更簡(jiǎn)潔。
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ā)生錯(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);
});
上面代碼中往核,getJSON()方法返回一個(gè) Promise 對(duì)象箫爷,如果該對(duì)象狀態(tài)變?yōu)閞esolved,則會(huì)調(diào)用then()方法指定的回調(diào)函數(shù)聂儒;如果異步操作拋出錯(cuò)誤虎锚,狀態(tài)就會(huì)變?yōu)閞ejected,就會(huì)調(diào)用catch()方法指定的回調(diào)函數(shù)衩婚,處理這個(gè)錯(cuò)誤窜护。另外,then()方法指定的回調(diào)函數(shù)非春,如果運(yùn)行中拋出錯(cuò)誤柱徙,也會(huì)被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));
下面是一個(gè)例子。
const promise = new Promise(function(resolve, reject) {
throw new Error('test');
});
promise.catch(function(error) {
console.log(error);
});
// Error: test
上面代碼中护侮,promise拋出一個(gè)錯(cuò)誤敌完,就被catch()方法指定的回調(diào)函數(shù)捕獲。注意概行,上面的寫法與下面兩種寫法是等價(jià)的蠢挡。
// 寫法一
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()方法的作用凳忙,等同于拋出錯(cuò)誤业踏。
如果 Promise 狀態(tài)已經(jīng)變成resolved,再拋出錯(cuò)誤是無(wú)效的涧卵。
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語(yǔ)句后面,再拋出錯(cuò)誤柳恐,不會(huì)被捕獲伐脖,等于沒(méi)有拋出。因?yàn)?Promise 的狀態(tài)一旦改變乐设,就永久保持該狀態(tài)讼庇,不會(huì)再變了。
Promise 對(duì)象的錯(cuò)誤具有“冒泡”性質(zhì)近尚,會(huì)一直向后傳遞蠕啄,直到被捕獲為止。也就是說(shuō)戈锻,錯(cuò)誤總是會(huì)被下一個(gè)catch語(yǔ)句捕獲歼跟。
getJSON('/post/1.json').then(function(post) {
return getJSON(post.commentURL);
}).then(function(comments) {
// some code
}).catch(function(error) {
// 處理前面三個(gè)Promise產(chǎn)生的錯(cuò)誤
});
上面代碼中,一共有三個(gè) Promise 對(duì)象:一個(gè)由getJSON()產(chǎn)生格遭,兩個(gè)由then()產(chǎn)生哈街。它們之中任何一個(gè)拋出的錯(cuò)誤,都會(huì)被最后一個(gè)catch()捕獲拒迅。
一般來(lái)說(shuō)骚秦,不要在then()方法里面定義 Reject 狀態(tài)的回調(diào)函數(shù)(即then的第二個(gè)參數(shù)),總是使用catch方法璧微。
// bad
promise
.then(function(data) {
// success
}, function(err) {
// error
});
// good
promise
.then(function(data) { //cb
// success
})
.catch(function(err) {
// error
});
上面代碼中骤竹,第二種寫法要好于第一種寫法,理由是第二種寫法可以捕獲前面then方法執(zhí)行中的錯(cuò)誤往毡,也更接近同步的寫法(try/catch)蒙揣。因此,建議總是使用catch()方法开瞭,而不使用then()方法的第二個(gè)參數(shù)懒震。
跟傳統(tǒng)的try/catch代碼塊不同的是罩息,如果沒(méi)有使用catch()方法指定錯(cuò)誤處理的回調(diào)函數(shù),Promise 對(duì)象拋出的錯(cuò)誤不會(huì)傳遞到外層代碼个扰,即不會(huì)有任何反應(yīng)瓷炮。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會(huì)報(bào)錯(cuò),因?yàn)閤沒(méi)有聲明
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 對(duì)象娘香,內(nèi)部有語(yǔ)法錯(cuò)誤。瀏覽器運(yùn)行到這一行办龄,會(huì)打印出錯(cuò)誤提示ReferenceError: x is not defined烘绽,但是不會(huì)退出進(jìn)程、終止腳本執(zhí)行俐填,2 秒之后還是會(huì)輸出123安接。這就是說(shuō),Promise 內(nèi)部的錯(cuò)誤不會(huì)影響到 Promise 外部的代碼英融,通俗的說(shuō)法就是“Promise 會(huì)吃掉錯(cuò)誤”盏檐。
這個(gè)腳本放在服務(wù)器執(zhí)行,退出碼就是0(即表示執(zhí)行成功)驶悟。不過(guò)胡野,Node.js 有一個(gè)unhandledRejection事件,專門監(jiān)聽(tīng)未捕獲的reject錯(cuò)誤痕鳍,上面的腳本會(huì)觸發(fā)這個(gè)事件的監(jiān)聽(tīng)函數(shù)给涕,可以在監(jiān)聽(tīng)函數(shù)里面拋出錯(cuò)誤。
process.on('unhandledRejection', function (err, p) {
throw err;
});
上面代碼中额获,unhandledRejection事件的監(jiān)聽(tīng)函數(shù)有兩個(gè)參數(shù),第一個(gè)是錯(cuò)誤對(duì)象恭应,第二個(gè)是報(bào)錯(cuò)的 Promise 實(shí)例抄邀,它可以用來(lái)了解發(fā)生錯(cuò)誤的環(huán)境信息。
注意昼榛,Node 有計(jì)劃在未來(lái)廢除unhandledRejection事件境肾。如果 Promise 內(nèi)部有未捕獲的錯(cuò)誤,會(huì)直接終止進(jìn)程胆屿,并且進(jìn)程的退出碼不為 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)”再拋出錯(cuò)誤环鲤。到了那個(gè)時(shí)候,Promise 的運(yùn)行已經(jīng)結(jié)束了憎兽,所以這個(gè)錯(cuò)誤是在 Promise 函數(shù)體外拋出的冷离,會(huì)冒泡到最外層吵冒,成了未捕獲的錯(cuò)誤。
一般總是建議西剥,Promise 對(duì)象后面要跟catch()方法痹栖,這樣可以處理 Promise 內(nèi)部發(fā)生的錯(cuò)誤。catch()方法返回的還是一個(gè) Promise 對(duì)象瞭空,因此后面還可以接著調(diào)用then()方法揪阿。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會(huì)報(bào)錯(cuò),因?yàn)閤沒(méi)有聲明
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
上面代碼運(yùn)行完catch()方法指定的回調(diào)函數(shù)咆畏,會(huì)接著運(yùn)行后面那個(gè)then()方法指定的回調(diào)函數(shù)南捂。如果沒(méi)有報(bào)錯(cuò),則會(huì)跳過(guò)catch()方法鳖眼。
Promise.resolve()
.catch(function(error) {
console.log('oh no', error);
})
.then(function() {
console.log('carry on');
});
// carry on
上面的代碼因?yàn)闆](méi)有報(bào)錯(cuò)黑毅,跳過(guò)了catch()方法,直接執(zhí)行后面的then()方法钦讳。此時(shí)矿瘦,要是then()方法里面報(bào)錯(cuò),就與前面的catch()無(wú)關(guān)了愿卒。
catch()方法之中缚去,還能再拋出錯(cuò)誤。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會(huì)報(bào)錯(cuò)琼开,因?yàn)閤沒(méi)有聲明
resolve(x + 2);
});
};
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log('oh no', error);
// 下面一行會(huì)報(bào)錯(cuò)易结,因?yàn)?y 沒(méi)有聲明
y + 2;
}).then(function() {
console.log('carry on');
});
// oh no [ReferenceError: x is not defined]
上面代碼中,catch()方法拋出一個(gè)錯(cuò)誤柜候,因?yàn)楹竺鏇](méi)有別的catch()方法了搞动,導(dǎo)致這個(gè)錯(cuò)誤不會(huì)被捕獲,也不會(huì)傳遞到外層渣刷。如果改寫一下鹦肿,結(jié)果就不一樣了。
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log('oh no', error);
// 下面一行會(huì)報(bào)錯(cuò)辅柴,因?yàn)閥沒(méi)有聲明
y + 2;
}).catch(function(error) {
console.log('carry on', error);
});
// oh no [ReferenceError: x is not defined]
// carry on [ReferenceError: y is not defined]
上面代碼中箩溃,第二個(gè)catch()方法用來(lái)捕獲前一個(gè)catch()方法拋出的錯(cuò)誤。
Promise.prototype.finally()
finally()方法用于指定不管 Promise 對(duì)象最后狀態(tài)如何碌嘀,都會(huì)執(zhí)行的操作涣旨。該方法是 ES2018 引入標(biāo)準(zhǔn)的。
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
上面代碼中股冗,不管promise最后的狀態(tài)霹陡,在執(zhí)行完then或catch指定的回調(diào)函數(shù)以后,都會(huì)執(zhí)行finally方法指定的回調(diào)函數(shù)。
下面是一個(gè)例子穆律,服務(wù)器使用 Promise 處理請(qǐng)求惠呼,然后使用finally方法關(guān)掉服務(wù)器。
server.listen(port)
.then(function () {
// ...
})
.finally(server.stop);
finally方法的回調(diào)函數(shù)不接受任何參數(shù)峦耘,這意味著沒(méi)有辦法知道剔蹋,前面的 Promise 狀態(tài)到底是fulfilled還是rejected。這表明辅髓,finally方法里面的操作泣崩,應(yīng)該是與狀態(tài)無(wú)關(guān)的,不依賴于 Promise 的執(zhí)行結(jié)果洛口。
finally本質(zhì)上是then方法的特例矫付。
promise
.finally(() => {
// 語(yǔ)句
});
// 等同于
promise
.then(
result => {
// 語(yǔ)句
return result;
},
error => {
// 語(yǔ)句
throw error;
}
);
上面代碼中,如果不使用finally方法第焰,同樣的語(yǔ)句需要為成功和失敗兩種情況各寫一次买优。有了finally方法,則只需要寫一次挺举。
它的實(shí)現(xiàn)也很簡(jiǎ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湘纵,都會(huì)執(zhí)行回調(diào)函數(shù)callback脂崔。
從上面的實(shí)現(xiàn)還可以看到,finally方法總是會(huì)返回原來(lái)的值梧喷。
// 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()方法用于將多個(gè) Promise 實(shí)例砌左,包裝成一個(gè)新的 Promise 實(shí)例。
const p = Promise.all([p1, p2, p3]);
上面代碼中铺敌,Promise.all()方法接受一個(gè)數(shù)組作為參數(shù)汇歹,p1、p2偿凭、p3都是 Promise 實(shí)例产弹,如果不是,就會(huì)先調(diào)用下面講到的Promise.resolve方法笔喉,將參數(shù)轉(zhuǎn)為 Promise 實(shí)例,再進(jìn)一步處理硝皂。另外常挚,Promise.all()方法的參數(shù)可以不是數(shù)組,但必須具有 Iterator 接口稽物,且返回的每個(gè)成員都是 Promise 實(shí)例奄毡。
p的狀態(tài)由p1、p2贝或、p3決定吼过,分成兩種情況锐秦。
(1)只有p1、p2盗忱、p3的狀態(tài)都變成fulfilled酱床,p的狀態(tài)才會(huì)變成fulfilled,此時(shí)p1趟佃、p2扇谣、p3的返回值組成一個(gè)數(shù)組,傳遞給p的回調(diào)函數(shù)闲昭。
(2)只要p1罐寨、p2、p3之中有一個(gè)被rejected序矩,p的狀態(tài)就變成rejected鸯绿,此時(shí)第一個(gè)被reject的實(shí)例的返回值,會(huì)傳遞給p的回調(diào)函數(shù)簸淀。
下面是一個(gè)具體的例子瓶蝴。
// 生成一個(gè)Promise對(duì)象的數(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 個(gè) Promise 實(shí)例的數(shù)組啃擦,只有這 6 個(gè)實(shí)例的狀態(tài)都變成fulfilled囊蓝,或者其中有一個(gè)變?yōu)閞ejected,才會(huì)調(diào)用Promise.all方法后面的回調(diào)函數(shù)令蛉。
下面是另一個(gè)例子聚霜。
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是兩個(gè)異步操作珠叔,只有等到它們的結(jié)果都返回了蝎宇,才會(huì)觸發(fā)pickTopRecommendations這個(gè)回調(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ò)了]
上面代碼中,p1會(huì)resolved霍骄,p2首先會(huì)rejected台囱,但是p2有自己的catch方法,該方法返回的是一個(gè)新的 Promise 實(shí)例读整,p2指向的實(shí)際上是這個(gè)實(shí)例簿训。該實(shí)例執(zhí)行完catch方法后,也會(huì)變成resolved,導(dǎo)致Promise.all()方法參數(shù)里面的兩個(gè)實(shí)例都會(huì)resolved强品,因此會(huì)調(diào)用then方法指定的回調(diào)函數(shù)膘侮,而不會(huì)調(diào)用catch方法指定的回調(diào)函數(shù)。
如果p2沒(méi)有自己的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ò)了
Promise.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)就跟著改變。那個(gè)率先改變的 Promise 實(shí)例的返回值要糊,就傳遞給p的回調(diào)函數(shù)纲熏。
Promise.race()方法的參數(shù)與Promise.all()方法一樣,如果不是 Promise 實(shí)例锄俄,就會(huì)先調(diào)用下面講到的Promise.resolve()方法局劲,將參數(shù)轉(zhuǎn)為 Promise 實(shí)例,再進(jìn)一步處理奶赠。
下面是一個(gè)例子鱼填,如果指定時(shí)間內(nèi)沒(méi)有獲得結(jié)果,就將 Promise 的狀態(tài)變?yōu)閞eject毅戈,否則變?yōu)閞esolve苹丸。
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方法無(wú)法返回結(jié)果苇经,變量p的狀態(tài)就會(huì)變?yōu)閞ejected赘理,從而觸發(fā)catch方法指定的回調(diào)函數(shù)。
Promise.allSettled()
有時(shí)候扇单,我們希望等到一組異步操作都結(jié)束了商模,不管每一個(gè)操作是成功還是失敗,再進(jìn)行下一步操作蜘澜。
但是施流,現(xiàn)有的 Promise 方法很難實(shí)現(xiàn)這個(gè)要求。
Promise.all()方法只適合所有異步操作都成功的情況鄙信,如果有一個(gè)操作失敗瞪醋,就無(wú)法滿足要求。
const urls = [url_1, url_2, url_3];
const requests = urls.map(x => fetch(x));
try {
await Promise.all(requests);
console.log('所有請(qǐng)求都成功扮碧。');
} catch {
console.log('至少一個(gè)請(qǐng)求失敗趟章,其他請(qǐng)求可能還沒(méi)結(jié)束。');
}
上面示例中慎王,Promise.all()可以確定所有請(qǐng)求都成功了蚓土,但是只要有一個(gè)請(qǐng)求失敗,它就會(huì)報(bào)錯(cuò)赖淤,而不管另外的請(qǐng)求是否結(jié)束蜀漆。
為了解決這個(gè)問(wèn)題,ES2020 引入了Promise.allSettled()方法咱旱,用來(lái)確定一組異步操作是否都結(jié)束了(不管成功或失斎范)。所以吐限,它的名字叫做”Settled“鲜侥,包含了”fulfilled“和”rejected“兩種情況。
Promise.allSettled()方法接受一個(gè)數(shù)組作為參數(shù)诸典,數(shù)組的每個(gè)成員都是一個(gè) Promise 對(duì)象描函,并返回一個(gè)新的 Promise 對(duì)象。只有等到參數(shù)數(shù)組的所有 Promise 對(duì)象都發(fā)生狀態(tài)變更(不管是fulfilled還是rejected)狐粱,返回的 Promise 對(duì)象才會(huì)發(fā)生狀態(tài)變更舀寓。
const promises = [
fetch('/api-1'),
fetch('/api-2'),
fetch('/api-3'),
];
await Promise.allSettled(promises);
removeLoadingIndicator();
上面示例中,數(shù)組promises包含了三個(gè)請(qǐng)求肌蜻,只有等到這三個(gè)請(qǐng)求都結(jié)束了(不管請(qǐng)求成功還是失敾ツ埂),removeLoadingIndicator()才會(huì)執(zhí)行蒋搜。
該方法返回的新的 Promise 實(shí)例篡撵,一旦發(fā)生狀態(tài)變更,狀態(tài)總是fulfilled齿诞,不會(huì)變成rejected酸休。狀態(tài)變成fulfilled后,它的回調(diào)函數(shù)會(huì)接收到一個(gè)數(shù)組作為參數(shù)祷杈,該數(shù)組的每個(gè)成員對(duì)應(yīng)前面數(shù)組的每個(gè) Promise 對(duì)象斑司。
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宿刮。它的回調(diào)函數(shù)接收到的參數(shù)是數(shù)組results。該數(shù)組的每個(gè)成員都是一個(gè)對(duì)象私蕾,對(duì)應(yīng)傳入Promise.allSettled()的數(shù)組里面的兩個(gè) Promise 對(duì)象僵缺。
results的每個(gè)成員是一個(gè)對(duì)象,對(duì)象的格式是固定的踩叭,對(duì)應(yīng)異步操作的結(jié)果磕潮。
// 異步操作成功時(shí)
{status: 'fulfilled', value: value}
// 異步操作失敗時(shí)
{status: 'rejected', reason: reason}
成員對(duì)象的status屬性的值只可能是字符串fulfilled或字符串rejected翠胰,用來(lái)區(qū)分異步操作是成功還是失敗。如果是成功(fulfilled)自脯,對(duì)象會(huì)有value屬性之景,如果是失敗(rejected)膏潮,會(huì)有reason屬性锻狗,對(duì)應(yīng)兩種狀態(tài)時(shí)前面異步操作的返回值。
下面是返回值的用法例子焕参。
const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];
const results = await Promise.allSettled(promises);
// 過(guò)濾出成功的請(qǐng)求
const successfulPromises = results.filter(p => p.status === 'fulfilled');
// 過(guò)濾出失敗的請(qǐng)求轻纪,并輸出原因
const errors = results
.filter(p => p.status === 'rejected')
.map(p => p.reason);
Promise.any()
ES2021 引入了Promise.any()方法。該方法接受一組 Promise 實(shí)例作為參數(shù)叠纷,包裝成一個(gè)新的 Promise 實(shí)例返回刻帚。
Promise.any([
fetch('https://v8.dev/').then(() => 'home'),
fetch('https://v8.dev/blog').then(() => 'blog'),
fetch('https://v8.dev/docs').then(() => 'docs')
]).then((first) => { // 只要有一個(gè) fetch() 請(qǐng)求成功
console.log(first);
}).catch((error) => { // 所有三個(gè) fetch() 全部請(qǐng)求失敗
console.log(error);
});
只要參數(shù)實(shí)例有一個(gè)變成fulfilled狀態(tài),包裝實(shí)例就會(huì)變成fulfilled狀態(tài)涩嚣;如果所有參數(shù)實(shí)例都變成rejected狀態(tài)我擂,包裝實(shí)例就會(huì)變成rejected狀態(tài)。
Promise.any()跟Promise.race()方法很像缓艳,只有一點(diǎn)不同校摩,就是Promise.any()不會(huì)因?yàn)槟硞€(gè) Promise 變成rejected狀態(tài)而結(jié)束,必須等到所有參數(shù) Promise 變成rejected狀態(tài)才會(huì)結(jié)束阶淘。
下面是Promise()與await命令結(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ù)組包含三個(gè) Promise 操作溪窒。其中只要有一個(gè)變成fulfilled坤塞,Promise.any()返回的 Promise 對(duì)象就變成fulfilled。如果所有三個(gè)操作都變成rejected澈蚌,那么await命令就會(huì)拋出錯(cuò)誤摹芙。
Promise.any()拋出的錯(cuò)誤是一個(gè) AggregateError 實(shí)例(詳見(jiàn)《對(duì)象的擴(kuò)展》一章),這個(gè) AggregateError 實(shí)例對(duì)象的errors屬性是一個(gè)數(shù)組宛瞄,包含了所有成員的錯(cuò)誤浮禾。
下面是一個(gè)例子。
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 instanceof AggregateError); // true
console.log(results.errors); // [-1, Infinity]
});
Promise.resolve()
有時(shí)需要將現(xiàn)有對(duì)象轉(zhuǎn)為 Promise 對(duì)象,Promise.resolve()方法就起到這個(gè)作用。
const jsPromise = Promise.resolve($.ajax('/whatever.json'));
上面代碼將 jQuery 生成的deferred對(duì)象叫编,轉(zhuǎn)為一個(gè)新的 Promise 對(duì)象。
Promise.resolve()等價(jià)于下面的寫法匆帚。
Promise.resolve('foo')
// 等價(jià)于
new Promise(resolve => resolve('foo'))
Promise.resolve()方法的參數(shù)分成四種情況。
(1)參數(shù)是一個(gè) Promise 實(shí)例
如果參數(shù)是 Promise 實(shí)例旁钧,那么Promise.resolve將不做任何修改吸重、原封不動(dòng)地返回這個(gè)實(shí)例互拾。
(2)參數(shù)是一個(gè)thenable對(duì)象
thenable對(duì)象指的是具有then方法的對(duì)象,比如下面這個(gè)對(duì)象嚎幸。
let thenable = {
then: function(resolve, reject) {
resolve(42);
}
};
Promise.resolve()方法會(huì)將這個(gè)對(duì)象轉(zhuǎn)為 Promise 對(duì)象摩幔,然后就立即執(zhí)行thenable對(duì)象的then()方法。
let thenable = {
then: function(resolve, reject) {
resolve(42);
}
};
let p1 = Promise.resolve(thenable);
p1.then(function (value) {
console.log(value); // 42
});
上面代碼中鞭铆,thenable對(duì)象的then()方法執(zhí)行后,對(duì)象p1的狀態(tài)就變?yōu)閞esolved焦影,從而立即執(zhí)行最后那個(gè)then()方法指定的回調(diào)函數(shù)车遂,輸出42。
(3)參數(shù)不是具有then()方法的對(duì)象斯辰,或根本就不是對(duì)象
如果參數(shù)是一個(gè)原始值舶担,或者是一個(gè)不具有then()方法的對(duì)象,則Promise.resolve()方法返回一個(gè)新的 Promise 對(duì)象彬呻,狀態(tài)為resolved衣陶。
const p = Promise.resolve('Hello');
p.then(function (s) {
console.log(s)
});
// Hello
上面代碼生成一個(gè)新的 Promise 對(duì)象的實(shí)例p。由于字符串Hello不屬于異步操作(判斷方法是字符串對(duì)象不具有 then 方法)闸氮,返回 Promise 實(shí)例的狀態(tài)從一生成就是resolved剪况,所以回調(diào)函數(shù)會(huì)立即執(zhí)行。Promise.resolve()方法的參數(shù)蒲跨,會(huì)同時(shí)傳給回調(diào)函數(shù)译断。
(4)不帶有任何參數(shù)
Promise.resolve()方法允許調(diào)用時(shí)不帶參數(shù),直接返回一個(gè)resolved狀態(tài)的 Promise 對(duì)象或悲。
所以孙咪,如果希望得到一個(gè) Promise 對(duì)象,比較方便的方法就是直接調(diào)用Promise.resolve()方法巡语。
const p = Promise.resolve();
p.then(function () {
// ...
});
上面代碼的變量p就是一個(gè) Promise 對(duì)象翎蹈。
需要注意的是,立即resolve()的 Promise 對(duì)象男公,是在本輪“事件循環(huán)”(event loop)的結(jié)束時(shí)執(zhí)行荤堪,而不是在下一輪“事件循環(huán)”的開(kāi)始時(shí)。
setTimeout(function () {
console.log('three');
}, 0);
Promise.resolve().then(function () {
console.log('two');
});
console.log('one');
// one
// two
// three
上面代碼中枢赔,setTimeout(fn, 0)在下一輪“事件循環(huán)”開(kāi)始時(shí)執(zhí)行逞力,Promise.resolve()在本輪“事件循環(huán)”結(jié)束時(shí)執(zhí)行,console.log('one')則是立即執(zhí)行糠爬,因此最先輸出寇荧。
Promise.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ò)了
上面代碼生成一個(gè) Promise 對(duì)象的實(shí)例p揩抡,狀態(tài)為rejected户侥,回調(diào)函數(shù)會(huì)立即執(zhí)行。
Promise.reject()方法的參數(shù)峦嗤,會(huì)原封不動(dòng)地作為reject的理由蕊唐,變成后續(xù)方法的參數(shù)。
Promise.reject('出錯(cuò)了')
.catch(e => {
console.log(e === '出錯(cuò)了')
})
// true
上面代碼中烁设,Promise.reject()方法的參數(shù)是一個(gè)字符串替梨,后面catch()方法的參數(shù)e就是這個(gè)字符串。
應(yī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;
});
};
Generator 函數(shù)與 Promise 的結(jié)合
使用 Generator 函數(shù)管理流程恋谭,遇到異步操作的時(shí)候糠睡,通常返回一個(gè)Promise對(duì)象。
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之中疚颊,有一個(gè)異步操作getFoo狈孔,它返回的就是一個(gè)Promise對(duì)象。函數(shù)run用來(lái)處理這個(gè)Promise對(duì)象材义,并調(diào)用下一個(gè)next方法均抽。
Promise.try()
實(shí)際開(kāi)發(fā)中,經(jīng)常遇到一種情況:
不知道或者不想?yún)^(qū)分其掂,函數(shù)f是同步函數(shù)還是異步操作到忽,但是想用 Promise 來(lái)處理它。
因?yàn)檫@樣就可以不管f是否包含異步操作清寇,都用then方法指定下一步流程喘漏,
用catch方法處理f拋出的錯(cuò)誤。一般就會(huì)采用下面的寫法华烟。
Promise.resolve().then(f)
上面的寫法有一個(gè)缺點(diǎn)翩迈,就是如果f是同步函數(shù),那么它會(huì)在本輪事件循環(huán)的末尾執(zhí)行盔夜。
const f = () => console.log('now');
Promise.resolve().then(f);
console.log('next');
// next
// now
上面代碼中负饲,函數(shù)f是同步的,但是用 Promise 包裝了以后喂链,就變成異步執(zhí)行了返十。
那么有沒(méi)有一種方法,讓同步函數(shù)同步執(zhí)行椭微,異步函數(shù)異步執(zhí)行洞坑,并且讓它們具有統(tǒng)一的 API 呢?回答是可以的蝇率,并且還有兩種寫法迟杂。第一種寫法是用async函數(shù)來(lái)寫刽沾。
const f = () => console.log('now');
(async () => f())();
console.log('next');
// now
// next
上面代碼中,第二行是一個(gè)立即執(zhí)行的匿名函數(shù)排拷,會(huì)立即執(zhí)行里面的async函數(shù)侧漓,因此如果f是同步的,就會(huì)得到同步的結(jié)果监氢;如果f是異步的布蔗,就可以用then指定下一步,就像下面的寫法浪腐。
(async () => f())()
.then(...)
需要注意的是纵揍,async () => f()會(huì)吃掉f()拋出的錯(cuò)誤。所以牛欢,如果想捕獲錯(cuò)誤,要使用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í)行的。
鑒于這是一個(gè)很常見(jiàn)的需求腊脱,所以現(xiàn)在有一個(gè)提案访得,提供Promise.try方法替代上面的寫法。
const f = () => console.log('now');
Promise.try(f);
console.log('next');
// now
// next
事實(shí)上陕凹,Promise.try存在已久悍抑,Promise 庫(kù)Bluebird、Q和when杜耙,早就提供了這個(gè)方法搜骡。
由于Promise.try為所有操作提供了統(tǒng)一的處理機(jī)制,所以如果想用then方法管理流程佑女,最好都用Promise.try包裝一下记靡。這樣有許多好處,其中一點(diǎn)就是可以更好地管理異常团驱。
function getUsername(userId) {
return database.users.get({id: userId})
.then(function(user) {
return user.name;
});
}
上面代碼中摸吠,database.users.get()返回一個(gè) Promise 對(duì)象,如果拋出異步錯(cuò)誤嚎花,可以用catch方法捕獲寸痢,就像下面這樣寫。
database.users.get({id: userId})
.then(...)
.catch(...)
但是database.users.get()可能還會(huì)拋出同步錯(cuò)誤(比如數(shù)據(jù)庫(kù)連接錯(cuò)誤紊选,具體要看實(shí)現(xiàn)方法)轿腺,這時(shí)你就不得不用try...catch去捕獲两嘴。
try {
database.users.get({id: userId})
.then(...)
.catch(...)
} catch (e) {
// ...
}
上面這樣的寫法就很笨拙了,這時(shí)就可以統(tǒng)一用promise.catch()捕獲所有同步和異步的錯(cuò)誤族壳。
Promise.try(() => database.users.get({id: userId}))
.then(...)
.catch(...)
事實(shí)上憔辫,Promise.try就是模擬try代碼塊,就像promise.catch模擬的是catch代碼塊仿荆。