Angular $http difference between .success() and .then()

后端 未结 4 1046
半阙折子戏
半阙折子戏 2021-01-24 23:47

Sometimes I have trouble to fetch my data using $http service. And I did not 100% understand the main difference between .success() and .then()

The following is an examp

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-25 00:11

    The other answers touch on how success receives just the data, but then doesn't. However, the implication is far more than that:

    $http() (or any of it's shortcut methods) will return a promise that has had its prototype augmented. The prototype gains the success and error methods. Both of these methods essentially function more like callbacks than anything else; whilst invoking success and passing it a callback will return the original promise back, that's where the similarities with promises end.

    success/error cannot be chained. That is, when you return a value from then in a promise, it will be passed to the next invocation of then. In this sense, promises can be chained. In addition, returning a promise in a then will resolve that promise before passing the resolved value to the next then invocation.

    success/error cannot do this, they are instead used to introduce side effects. Any values you return from these functions are discarded. They also do not receive the raw http response, but instead just the data from the endpoint. Multiple success/error calls will set up independent callbacks. In addition, there is no way to 'wait' for a success/error callback to have been finished executing. So Q.all() won't work on success/error callbacks if those success/error callbacks fire off async events.

    As a result I would recommend you only use then/catch in place of success/error. This allows you to keep compatibility with other frameworks that handle promises, and also will allow you to chain promises to further manipulate data. It also helps you prevent side effects, and everyone loves preventing side effects!

提交回复
热议问题