【问题标题】:How to avoid repetition of .then() and .catch() after $http requests?如何避免在 $http 请求后重复 .then() 和 .catch()?
【发布时间】:2015-02-23 04:57:29
【问题描述】:

我的 Angular 应用中有一个简单的 userAPI 服务:

app.service('userAPI', function ($http) {
this.create = function (user) {
    return $http
        .post("/api/user", { data: user })
        .then(function (promise) { return promise.data })
        .catch(function (error) { return error.data })
}

this.read = function (user) {
    return $http
        .get("/api/user/" + user.id)
        .then(function (promise) { return promise.data })
        .catch(function (error) { return error.data })
}

this.update = function (user) {
    return $http
        .patch("/api/user/" + user.id, { data: user })
        .then(function (promise) { return promise.data })
        .catch(function (error) { return error.data })
}

this.delete = function (user) {
    return $http
        .delete("/api/user/" + user.id)
        .then(function (promise) { return promise.data })
        .catch(function (error) { return error.data })
}
})

如您所见,我在每个 $http 请求之后重复相同的 .then() 和 .catch() 函数。我可以根据 DRY 原则避免这种重复吗?

【问题讨论】:

  • 我看不出那些回调有什么作用...
  • 为什么不在控制器中捕获错误(或在任何你使用userAPI 服务的地方)?
  • 另外,更重要的是,你为什么不使用 $resource 呢???

标签: javascript angularjs promise dry


【解决方案1】:

为什么不只编写一次函数并将它们应用于服务中的每个回调?

类似:

app.service('userAPI', function ($http) {
    var success = function (response) { return response.data; },
        error = function (error) { return error.data; };

    this.create = function (user) {
        return $http
          .post("/api/user", { data: user })
          .then(success, error);
    }
    this.read = function (user) {
      return $http
        .get("/api/user/" + user.id)
        .then(success, error);
    };
    this.update = function (user) {
      return $http
        .patch("/api/user/" + user.id, { data: user })
        .then(success, error);
    };
    this.delete = function (user) {
      return $http
        .delete("/api/user/" + user.id)
        .then(success, error);
    };
});

另外请注意,您可以使用 then(successcallback, errorcallback, notifycallback) 来缩短代码,甚至比使用 then/catch 还要短。

【讨论】:

  • 这是你能为这种异步事情做的最好和最多的事情......!
  • 为了将错误保留在失败路径上,应该抛出error.data,而不是返回。
  • 或者可能是 return $q.reject(error.data); 和 $q。 令人困惑
  • Roamer 所说的是正确的 - 还要注意 .then(success, error) 所做的事情与 .then(success).catch(error) 不同。
猜你喜欢
  • 1970-01-01
  • 2016-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2021-03-12
相关资源
最近更新 更多