【问题标题】:difference between “Promise reject” with “try-catch”“Promise reject”与“try-catch”的区别
【发布时间】:2017-08-07 02:18:31
【问题描述】:
var promise = new Promise(function(resolve, reject) {
  try {
    throw new Error('test');
  } catch(e) {
    reject(e);
  }
});
promise.catch(function(error) {
  console.log(error);
});

我们可以使用“try-catch”来抛出错误

// mothod 2
var promise = new Promise(function(resolve, reject) {
  reject(new Error('test'));
});
promise.catch(function(error) {
  console.log(error);
});

我们也可以使用“reject”来抛出错误。

它们有什么区别?

【问题讨论】:

标签: ecmascript-6 promise


【解决方案1】:
  1. 无法使用 try-catch 块处理从异步函数引发的异常。
  2. Promise 是可链接的;防止我们嵌套影响可读性的代码。

【讨论】:

    【解决方案2】:

    没有有效的区别。在这两种情况下,您调用 reject() 时都会出错。

    以下内容也等同于您那里的内容:

    var promise = new Promise(function(resolve, reject) {
      throw new Error('test');
    });
    
    
    var promise = Promise.reject(new Error('test'));
    
    
    var promise = Promise.resolve().then(function () { throw new Error('test'); });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-20
      • 2011-02-20
      • 2010-12-14
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多