I need to return a customized response in a promise, from an $http call, so I can chain further calls. I have two implementations available. Can someone explain the difference between two, and argue if one is better?
In fooService.js
Implementation #1
function foo() {
var deferred = $q.defer();
return $http.get('some-http-url')
.then(function(response) {
var data = response.data.Data;
// Some manipulation on data
deferred.resolve(data);
return deferred.promise;
});
}
Implementation #2
function foo() {
return $http.get('some-http-url')
.then(function(response) {
var data = response.data.Data;
// Some manipulation on data
return $q.resolve(data);
});
}
And then in FooController.js
fooService.foo().then(function(response) {
// Do something
});
P.S. Some links, that can give me a better understanding are welcome.
**************UPDATE 4th October, 2017**************
If I modify my function foo() like this
Implementation #1
function foo() {
var deferred = $q.defer();
if(/*some condition*/) {
deferred.resolve('data');
return deferred.promise;
}
else {
deferred.reject('error');
return deferred.promise;
}
}
Implementation #2
function foo() {
if(/*some condition*/)
return $q.resolve('data');
else
return $q.reject('error');
}
Which is the preferred way?
You don't need $q
here at all, because $http
already returns a promise.
Just return data in .then()
and it will be available for the next .then()
in the chain:
function foo() {
return $http.get('some-http-url')
.then(function(response) {
return response.data.Data;
});
}
The way you are doing your implementation is called deferred antipattern, more info in this answer.