【问题标题】:What is the best way to handle errors for promises?处理承诺错误的最佳方法是什么?
【发布时间】:2017-12-26 09:32:27
【问题描述】:

我有一个配置加载函数,它从 json 文件加载一些数据并用它解决一个承诺。

当我调用加载函数时,我想知道处理错误的更好方法是什么。据我了解,可以有两种选择。

public config: any = this.configProvider.load()
    .then(data => this)
    .then(error => console.error(error));

public config: any = this.configProvider.load()
    .then(data => this)
    .catch(function(err){
        console.log(err);
    }

【问题讨论】:

标签: javascript angular typescript promise es6-promise


【解决方案1】:

.catch 是个不错的选择。

.catch 在加载 json / 无效 json 的过程中捕获错误,无论是否发生错误,都执行双重 .then。所以如果你没有出错,第二个.then 仍然会执行

【讨论】:

    【解决方案2】:

    它们都实现了记录错误的相同目标。但是,当您进入箭头函数时,上下文不会改变。 this 的值将在 function 块内更改。例如,如果您需要使用与包含您的函数的对象关联的键,则最好使用function 块,因为您可以使用this 关键字来引用封闭对象。 此外,据我所知,在链的末尾使用 .catch 将捕获到该点之前在 Promise 链中遇到的任何错误。但是,使用 .then 将捕获紧接在前面的 .then 块的错误,而不是之前的任何错误。

    【讨论】:

      【解决方案3】:

      此代码不正确:

      public config: any = this.configProvider.load()
          .then(data => this)
          .then(error => console.error(error));
      

      它不会捕获任何错误。错误是被拒绝的承诺。你需要的是这样的:

      public config: any = this.configProvider.load()
          .then(data => this, error => console.error(error))
      

      将捕获被拒绝的 Promise 的函数作为第二个参数传递。

      catch 的方法对我来说更具可读性和直观性:

      public config: any = this.configProvider.load()
          .then(...)
          .then(...)
          .then(...)
          .catch(function(err){
              console.log(err);
          }
      

      但是您可以通过以下方式实现相同的目的:

      public config: any = this.configProvider.load()
          .then(...)
          .then(...)
          .then(..., function(err){
              console.log(err);
          });
      

      【讨论】:

      • 谢谢,我最终选择了你的第一个例子!
      • @AugieLuebbers,不客气,感谢您的回答,祝您好运
      猜你喜欢
      • 1970-01-01
      • 2018-09-21
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 2017-11-13
      • 2018-11-18
      • 1970-01-01
      相关资源
      最近更新 更多