How to avoid repetition of .then() and .catch() af

2019-05-29 21:10发布

问题:

I have a simple userAPI service in my angular app:

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 })
}
})

As you can see, i am repeating same .then() and .catch() functions after each of my $http requests. Ho can i avoid this repitition according to DRY principle?

回答1:

Why not just write the functions once and apply them to each callback in the service?

Something like:

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);
    };
});

Also note you can use then(successcallback, errorcallback, notifycallback) to shorten your code even further than using then/catch.