"抛出新的错误()"在catch块上下文中捕获

时间:2016-06-21 17:27:06

标签: javascript asynchronous error-handling try-catch

我已经简化了下面代码中的方案,因为我没有足够的空间来解释我的用例,但基本上我是从" catch&#34中抛出一个错误;承诺的块。如何从该catch块传递错误(在下面的示例中,我希望从外部" catch"块中报告错误" try / catch"我把代码包裹起来了:)



var p = new Promise(function(resolve, reject) {
  setTimeout(function() {
    reject();
  }, 1000);


});

try {
  p.then(function() {
    console.log('promise resolved');
  }).catch(function() {
    throw new Error('I want to get out of this catch block!');
  });
} catch (err) {
  console.log('I want to report the error from here' + err.message);
}




1 个答案:

答案 0 :(得分:1)

Promise中的catch处理程序与promise本身一样异步,因此您无法从它们恢复为同步流/异常控制。您传递到.catch的功能可能会在它退出的try / catch周围之后才会被调用。

相关问题