0

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?

1 Answers1

3

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.

Stanislav Kvitash
  • 4,614
  • 18
  • 29
  • But the main question was the difference between ‍‍‍‍‍‍‍`$q.resolve(‍‍‍‍)` vs `deferred.resolve()`. – Pedram Aghazadeh Jun 18 '22 at 10:32
  • 1
    When there is a `$http` request, there is a `promise` and it can be returned. But if we had to write a function in such a way that if a request has already been sent and the data now exists it will return the `existing data`, in this case we will not have a promise. How can we return the result without making a `promise` so that we can use the `then` chain? – Pedram Aghazadeh Jun 18 '22 at 10:39