第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

promise內(nèi)部拋出錯(cuò)誤,catch不到求指導(dǎo)!

promise內(nèi)部拋出錯(cuò)誤,catch不到求指導(dǎo)!

郎朗坤 2019-09-09 21:06:17
阮一峰的ECMAScript6入門Promise對(duì)象第四小節(jié)提到:promise拋出一個(gè)錯(cuò)誤,就被catch方法指定的回調(diào)函數(shù)捕獲。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);});請(qǐng)問:為什么如下的形式,catch無法捕獲錯(cuò)誤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貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個(gè)贊

constpromise=newPromise(function(resolve,reject){
setTimeout(function(){thrownewError('test')},0)
});
promise.catch(function(error){console.log(error)});
JS事件循環(huán)列表有宏任務(wù)與微任務(wù)之分:setTimeOut是宏任務(wù),promise是微任務(wù),他們有各自的執(zhí)行順序;因此這段代碼的執(zhí)行是:
代碼執(zhí)行棧進(jìn)入promise觸發(fā)setTimeOut,此時(shí)setTimeOut回調(diào)函數(shù)加入宏任務(wù)隊(duì)列
代碼執(zhí)行promise的catch方法(微任務(wù)隊(duì)列)此時(shí)setTimeOut回調(diào)還沒有執(zhí)行
執(zhí)行棧檢查發(fā)現(xiàn)當(dāng)前微任務(wù)隊(duì)列執(zhí)行完畢,開始執(zhí)行宏任務(wù)隊(duì)列
執(zhí)行thrownewError('test')此時(shí)這個(gè)異常其實(shí)是在promise外部拋出的
constpromise=newPromise(function(resolve,reject){
setTimeout(function(){
try{
thrownewError('test')
}catch(e){
reject(e)
}
},0)
});
是因?yàn)槟阍趕etTimeOut主動(dòng)觸發(fā)了promise的reject方法,因此promise的catch將會(huì)在setTimeOut回調(diào)執(zhí)行后的屬于他的微任務(wù)隊(duì)列中找到它然后執(zhí)行,所以可以捕獲錯(cuò)誤
                            
查看完整回答
反對(duì) 回復(fù) 2019-09-09
  • 2 回答
  • 0 關(guān)注
  • 1818 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)