【问题标题】:In AngularJS, does every then require a catch?在 AngularJS 中,是否每次都需要捕获?
【发布时间】:2018-11-15 08:45:36
【问题描述】:

我正在执行多个 ajax 调用,并且我想在显示我的表单之前完成所有这些调用。如果有错误,我想停止处理并只显示遇到的第一个错误。我在 Google 上搜索了很多文章,包括 StackOverflow 上的文章,这些文章展示了如何链接 then 语句。但似乎我必须在每个 then 上附加一个 catch,否则只会捕获最后一条语句中的错误。在这个例子中,Lookup 是一个异步调用,它返回一个 promise,ShowError 处理错误:

Data.Lookup("a")
  .then(function(result) {
    vm.a = result;
    Data.Lookup("b")
      .then(function(result) {
        vm.b = result;
        Data.Lookup("c")
          .then(function(result) {
            vm.c = result;
          })
          .catch(function(response) {
            vm.showError(response);
          });
      })
      .catch(function(response) {
        vm.showError(response);
      });
  })
  .catch(function(response) {
    vm.showError(response);
  });

假设至少有一个错误,有没有办法使用单个 catch,当遇到第一个错误时触发?

这是与问题Wait for all promises to resolve 不同的要求。如标题所述,该用户想要处理所有承诺。当第一个承诺出现错误时,我很高兴退出。

【问题讨论】:

标签: angularjs error-handling try-catch


【解决方案1】:

添加返回,因此如果内部失败之一,则结果承诺失败:

Data.Lookup("a")
  .then(function(result) {
    vm.a = result;
    return Data.Lookup("b")
      .then(function(result) {
        vm.b = result;
        return Data.Lookup("c")
          .then(function(result) {
            vm.c = result;
          });
      });
  })
  .catch(function(response) {
    vm.showError(response);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-04
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2021-02-24
    • 2021-07-19
    相关资源
    最近更新 更多