2

I have this code in a service, it works for me. As far as I know, $http.get() returns a promise, promise executes asynchronously, so why do I need to use deffered.resolve(res.data) to return data in my service. Thanks a lot.

 data.posts = function(page, perPage, format, orderBy) {
        var deffered = $q.defer();
        $http.get(hostName, {
            params: {
                'page': page,
                'per_page': perPage,
                'filter[post_format]=': format,
                'filter[orderby]=': orderBy,
                'order': 'desc'
            }
        }).then(function(res) {
            deffered.resolve(res.data);
        })
        return deffered.promise;
    }
attomos
  • 1,112
  • 3
  • 16
  • 30
beo dan
  • 31
  • 2

2 Answers2

0

If truly in a service, deferred not needed. The method in the service returns the promise from the above $http request.

function exampleService($http) {
    var data = this;
    data.post = function(page, perPage, format, orderBy) {
      return $http.get(hostName, {
          params: {
            'page': page,
            'per_page': perPage,
            'filter[post_format]=': format,
            'filter[orderby]=': orderBy,
            'order': 'desc'
          }
        }).then(function(res) {
          //do stuff with success
        })
        .catch(function(err) {
          //do stuff with error
        })
        .finally(function() {
          //optionally use this as well maybe if you had loading type overlay/icon
        });
    };
  }
  //preferred method as it makes methods available before the sevice has been returned  

function exampleService($http) {
  function post(page, perPage, format, orderBy) {
      return $http.get(hostName, {
          params: {
            'page': page,
            'per_page': perPage,
            'filter[post_format]=': format,
            'filter[orderby]=': orderBy,
            'order': 'desc'
          }
        }).then(function(res) {
          //do stuff with success
        })
        .catch(function(err) {
          //do stuff with error
        })
        .finally(function() {
          //optionally use this as well maybe if you had loading type overlay/icon
        });
    }
    //revealing module pattern 
  return {
    post: post,

  };
}
alphapilgrim
  • 3,761
  • 8
  • 29
  • 58
0

Why use it? Because the author didn't know better. There are however many reasons not to use it.

The code should read

data.posts = function(page, perPage, format, orderBy) {
    return $http.get(hostName, {
        params: {
            'page': page,
            'per_page': perPage,
            'filter[post_format]=': format,
            'filter[orderby]=': orderBy,
            'order': 'desc'
        }
    }).then(function(res) {
        return res.data;
    });
};
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375