阮一峰的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)});
promise內(nèi)部拋出錯(cuò)誤,catch不到求指導(dǎo)!
郎朗坤
2019-09-09 21:06:17