javascript - 為什么嵌套的Promise不能按預期捕獲Exception?
問題描述
我有如下的代碼,本來期望‘core exception’ 可以被 ‘立即執行的函數(見最后)’捕獲到,并打印出“Got it in main scope”,但沒有按預期執行,即'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'); }})();
程序運行結果為
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.
誰幫忙解釋一下?非常感謝!
我使用的是node v7.2.1
問題解答
回答1:簡化的例子是這樣的:
function core() { return new Promise(async (fulfill, reject) => {// Promise constructor的參數的返回值是被無視的// 加個async不會導致新Promise被連接到fulfill或reject// 所以下面的那個Promise不會被then或catch,成為你看到的現象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這個地方的Promise既沒有resolve,也沒有reject,所以你要怎樣呢?^^
回答3:為什么我只有做如下的修改,才能得到預期的結果呢? 是不是和microtask有關呢?誰能幫忙清楚地解釋一下?
’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'); }})();
得到的運行結果為:
wrapper exception risescore promise rejected - core exception risesmain exception propagatedGot it in main scope回答4:
<script>alert(‘s’)</script>
相關文章:
1. javascript - react+百度地圖2. html5 - iOS的webview加載出來的H5網頁,怎么修改html標簽select的樣式字體?3. vue.js - vue+webpack+vue-router 部署到nginx服務器下,非根目錄,前后端怎樣配置文件?4. javascript - 為什么當index等于5的時候,不在當前頁面跳轉到百度?不跳轉的代碼在倒數第五行5. angular.js - 關于angular react vue 我們在什么實際的開發項目中使用?如何選擇?6. 手動啟動mysql服務出錯,1067錯誤,如何解決呢?7. index.php錯誤,求指點8. 這是什么情況???9. 請教一條mysql的sql語句寫法;10. 跟著課件一模一樣的操作使用tp6,出現了錯誤
