Reputation: 24562
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
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
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
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
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