亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

promise內部拋出錯誤,catch不到求指導!

promise內部拋出錯誤,catch不到求指導!

郎朗坤 2019-09-09 21:06:17
阮一峰的ECMAScript6入門Promise對象第四小節提到:promise拋出一個錯誤,就被catch方法指定的回調函數捕獲。constpromise=newPromise(function(resolve,reject){thrownewError('test');});promise.catch(function(error){console.log(error);});等同于://寫法一constpromise=newPromise(function(resolve,reject){try{thrownewError('test');}catch(e){reject(e);}});promise.catch(function(error){console.log(error);});//寫法二constpromise=newPromise(function(resolve,reject){reject(newError('test'));});promise.catch(function(error){console.log(error);});請問:為什么如下的形式,catch無法捕獲錯誤constpromise=newPromise(function(resolve,reject){setTimeout(function(){thrownewError('test')},0)});promise.catch(function(error){console.log(error)});但如果改成如下兩種形式就可以。//改寫方法1constpromise=newPromise(function(resolve,reject){setTimeout(function(){try{thrownewError('test')}catch(e){reject(e)}},0)});//改寫方法2constpromise=newPromise(function(resolve,reject){setTimeout(function(){reject(newError('test'));},0)});
查看完整描述

2 回答

?
皈依舞

TA貢獻1851條經驗 獲得超3個贊

constpromise=newPromise(function(resolve,reject){
setTimeout(function(){thrownewError('test')},0)
});
promise.catch(function(error){console.log(error)});
JS事件循環列表有宏任務與微任務之分:setTimeOut是宏任務,promise是微任務,他們有各自的執行順序;因此這段代碼的執行是:
代碼執行棧進入promise觸發setTimeOut,此時setTimeOut回調函數加入宏任務隊列
代碼執行promise的catch方法(微任務隊列)此時setTimeOut回調還沒有執行
執行棧檢查發現當前微任務隊列執行完畢,開始執行宏任務隊列
執行thrownewError('test')此時這個異常其實是在promise外部拋出的
constpromise=newPromise(function(resolve,reject){
setTimeout(function(){
try{
thrownewError('test')
}catch(e){
reject(e)
}
},0)
});
是因為你在setTimeOut主動觸發了promise的reject方法,因此promise的catch將會在setTimeOut回調執行后的屬于他的微任務隊列中找到它然后執行,所以可以捕獲錯誤
                            
查看完整回答
反對 回復 2019-09-09
  • 2 回答
  • 0 關注
  • 1824 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號