javascript - 為什么嵌套的Promise不能按預(yù)期捕獲Exception?
問題描述
我有如下的代碼,本來(lái)期望‘core exception’ 可以被 ‘立即執(zhí)行的函數(shù)(見最后)’捕獲到,并打印出“Got it in main scope”,但沒有按預(yù)期執(zhí)行,即'Got it in main scope'沒有打印。
’use strict’; function core() { function wrapper() {return new Promise((resolve, reject) => { throw new Error('wrapper exception rises');}); } return new Promise(async (resolve, reject) => {try { await wrapper();} catch(error) { console.error(error.message); throw new Error('core exception rises');} });} (async function() { try {await core(); } catch(error) {console.error(error.message);console.error('Got it in main scope'); }})();
程序運(yùn)行結(jié)果為
wrapper exception rises(node:10093) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): Error: core exception rises(node:10093) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
誰(shuí)幫忙解釋一下?非常感謝!
我使用的是node v7.2.1
問題解答
回答1:簡(jiǎn)化的例子是這樣的:
function core() { return new Promise(async (fulfill, reject) => {// Promise constructor的參數(shù)的返回值是被無(wú)視的// 加個(gè)async不會(huì)導(dǎo)致新Promise被連接到fulfill或reject// 所以下面的那個(gè)Promise不會(huì)被then或catch,成為你看到的現(xiàn)象return Promise.reject(new Error('core exception rises')); });};core();回答2:
改改:
return new Promise(async (resolve, reject) => { try {await wrapper(); } catch(error) {reject(new Error('core exception rises')); }});
或者:
return (async function( ) { try {await wrapper(); } catch(error) {console.error(error.message);throw new Error('core exception rises'); }}());
你代碼的問題是,core exception rises這個(gè)地方的Promise既沒有resolve,也沒有reject,所以你要怎樣呢?^^
回答3:為什么我只有做如下的修改,才能得到預(yù)期的結(jié)果呢? 是不是和microtask有關(guān)呢?誰(shuí)能幫忙清楚地解釋一下?
’use strict’; function core() { function wrapper() {return new Promise((resolve, reject) => { throw new Error('wrapper exception rises');}); } return new Promise(async (resolve, reject) => {try { await wrapper();} catch(error) { console.error(error.message); //throw new Error('core exception rises'); reject(new Error('core exception rises'));} });} (async function() { try {await core().catch(err => { console.log('core promise rejected - ' + err.message); throw new Error('main exception propagated');}); } catch(error) {console.error(error.message);console.error('Got it in main scope'); }})();
得到的運(yùn)行結(jié)果為:
wrapper exception risescore promise rejected - core exception risesmain exception propagatedGot it in main scope回答4:
<script>alert(‘s’)</script>
相關(guān)文章:
1. docker網(wǎng)絡(luò)端口映射,沒有方便點(diǎn)的操作方法么?2. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?3. Java:密碼包(加密和解密)。無(wú)效的密鑰錯(cuò)誤4. css - 微信小程序點(diǎn)擊展開,再次點(diǎn)擊收回5. 點(diǎn)擊頁(yè)面就自動(dòng)輸入到mysql.求解6. macos - mac下docker如何設(shè)置代理7. css - vue.js的vue單文件組件style中的scoped屬性無(wú)效8. angular.js - 在ng-option 里使用過濾器無(wú)效9. node.js - 求問nw.js開發(fā)桌面版,其js計(jì)算性能如何?10. 我在centos容器里安裝docker,也就是在容器里安裝容器,報(bào)錯(cuò)了?
