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