AngularJS: Return a promise that is built from the result of another promise in angular?

I have the following function defined in a service that I use $http

to get some data and set some fields of an object:

function getComplexObject () {

    var complexObject = {
        'A': null,
        'B': null
    }
    $http.get('someURI').then(function(data) {
        complexObject.A = data;

        //Do some processing and set B 

        return complexObject;
    })
};

      

So, so far I have been using a promise with a service $http

, but I don't know how to wrap the function with $q

so that I can end up using it like this:

//Using my function as a promise
myService.getComplexObject().then(function (data) {
    this.complexObject = data;
})

      

I have looked for tutorials on angular promises but most of them just explain what a promise is or something similar to what I already did, I guess what I want to do, but it is possible, but I may not find the correct syntax or correct tutorial.

+3


source to share


2 answers


Just put return

before the chain $http.get(...).then(...)

, i.e.

return $http.get(...).then(...);

      

This ensures that the result getComplexObject

is a promise that (when resolved) will contain a value complexObject

.



This is exactly what it is intended for .then

- it takes the promise from itself $http.get()

and returns a new promise that will eventually resolve with its own return value instead of the original one.

FWIW, I would put the declaration complexObject

inside the call .then

- there is no need for it to be in the outer scope, and it will inadvertently cause that variable to be closed.

NB: Also be careful about using this

in your last callback - it might not be what you think!

+3


source


You can return the promise and decide if later (see: https://docs.angularjs.org/api/ng/service/ $ q).



function getComplexObject () {

    var deferred = $q.defer();
    var complexObject = {
        'A': null,
        'B': null
    }
    $http.get('someURI').then(function(data) {
        complexObject.A = data;

        //Do some processing and set B 
        deferred.resolve(complexObject);
    });
    return deferred.promise;
};

      

0


source







All Articles