Alan2
Alan2

Reputation: 24562

How can I return a promise from a function that calls a $http.get in AngularJS?

I have the following function:

   getX: function ($scope) {
       $http.get('/api/X/GetSelect')
           .success(function (data) {
               ...
               ...
           })
           .error(function (data) {
               ...
           });
   },

I want this to always do the things in the .success block but I would like it to also return a promise so that I can call it like this:

getX($scope)
   .then( function () {
       doNextThing();
}

Can someone help by telling me how I can code it so a promise is returned?

Upvotes: 1

Views: 110

Answers (4)

SrikanthManian
SrikanthManian

Reputation: 148

You might need to use a deferred promise. This is how you could do it.

var functionA = function () {
    var deferred = $q.defer();
    $http.get('url here').
          success(function (response) {
              deferred.resolve(response);
          }).
          error(function (response) {
          });
    return deferred.promise;
}

Now calling functionA should return you a promise on which you can perform manipulations as you needed.

Upvotes: 1

thomaux
thomaux

Reputation: 19718

Easy, you return a promise yourself. You need to inject $q for this (take a look at the docs for more information).

Then you can update your code to:

getX: function ($scope) {
    var defer = $q.defer();
    $http.get('/api/X/GetSelect').success(function (data) {
        ...
        ...
        defer.resolve();
    }).error(function (data) {
        ...
        defer.reject();
    });
    return defer.promise;
}

Upvotes: 3

Alborz
Alborz

Reputation: 6903

function getX($scope)
{
    var defered = $q.defer();
     $http.get('/api/X/GetSelect')
               .success(function (data) {
                   defered.resolve(data);
                   ...
               })
               .error(function (data) {
                   defered.reject();
               });
    return defered.promise();
    }

You need to inject $q into your contorller.

Upvotes: 2

Vinoth
Vinoth

Reputation: 647

You just add the return statement before the $http.get() method. This will return the promise.

Example:

 return $http.get('/api/X/GetSelect')
       .success(function (data) {
           ...
           ...
       })
       .error(function (data) {
           ...
       });

Upvotes: 5

Related Questions