javascript - 如何避免 $http 请求后重复 .then() 和 .catch() ?

标签 javascript angularjs promise dry

我的 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 原则避免这种重复?

最佳答案

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

类似于:

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, notificationcallback) 比使用 then/catch 进一步缩短代码。

关于javascript - 如何避免 $http 请求后重复 .then() 和 .catch() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28667147/

相关文章:

javascript - Firefox 扩展如何最好地避免污染全局命名空间?

Javascript object.create 和 isPrototypeOf

asp.net - html 脚本标签不使用类型 javascript <脚本类型 ="text/html">?

javascript - 如何在 Mean Stack 中运行子进程

javascript - 如何验证某些字段并在 ng-click AngularJS 上进行选择

javascript - bs-工具提示类型错误 : Cannot read property 'nodeName' of undefined

typescript - 将接口(interface)中的字段类型替换为 promise

javascript - 用 Angular 绑定(bind) svg 属性

javascript - 将一系列有序操作组合成一个 Observable

javascript - 我无法在 .then() Promise 中返回对象