I'm having a bit of a brainmelt with promises at the moment.
Given the following code:
$scope.getData = function(user) {
return $http.post('/endpoint', "some post data", { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
.success(function (response) {
var myThing = { stuff: response.infoData };
localStorageService.set('myData', { stuff: response.infoData });
return myThing;
});
};
Is the myThing object that is returned from the success callback:
From what I understand:
Is this correct? Is there something I'm missing, is there some benefit to returning objects in the success method, or is the return superfluous? (I'm well aware that this is code can be improved but I'm trying to find out specifically why someone would have written this, or if it was entirely a mistake)
Using success/error
callbacks over $http
method wouldn't give you ability to return a data from it. Where as promise does provide that ability. The way it has written currently would do what it seems. Like myThing
will not return by current implementation(that is redundant return statement there).
Why someone would have written this, or if it was entirely a mistake?
Whoever implemented this method was trying to return a data from it, but I don't think so he is succeeded in that by looking at current code.
To Take advantage of promise returned by $http
method's which will give you capabilities to form promise chain over async call. For that you need to use .then
instead of .success
method.
$scope.getData = function(user) {
return $http.post('/endpoint', "some post data", { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
.then(function (res) {
var response = res.data;
var myThing = { stuff: response.infoData };
localStorageService.set('myData', { stuff: response.infoData });
return myThing;
});
};
If you really interested to retrieve data by calling getData
method, then you could consume getData
method you should put .then
function over promise returned by it to chain it.
$scope.getData().then(function(thing){
console.log(thing);
})
Side Note
.success
&error
function over$http
methods are deprecated .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.