genkio / blog

Stay hungry stay foolish
https://slashbit.github.io/blog/
0 stars 1 forks source link

Differences between return $http.get and $http.get().then() #108

Open genkio opened 7 years ago

genkio commented 7 years ago
  this.getComments = function(type, targetId) {
    return $http.get('/api/comments/' + type + '/' + targetId);
  };

See what does it returns: image

  this.getComments = function(type, targetId) {
    return $http.get('/api/comments/' + type + '/' + targetId)
      .then(function(response) {
        return response.data;
      });
  };

And now see the differences: image

To summarise,

Do it the right way:

  this.getComments = function(type, targetId) {
    return $http.get(this.baseUrl + type + '/' + targetId)
      .then(function(response) {
        return response.data;
      });
  };

another way to do it (with $q as dependency)

this.getComments = function(type, targetId) {
  var deferred = $q.defer();
  $http.get('/api/comments/' + type + '/' + targetId)
    .then(function(success) {
      deferred.resolve(success.data);
    }, function(error) {
      deferred.reject(error);
  return $http.get(this.baseUrl + type + '/' + targetId)
    .then(function(response) {
      return response.data;
    });
  return deferred.promise;
};
  $comment.getComments($C.commentTypes['1'], $scope.detail.pid)
    .then(function(data) {
      $scope.comments = data.rows;
      $scope.commentsCount = data.count;
    }).catch(function(response) {
      $modal.open({ message: '评论加载失败', type: 'error' });
    });