简体   繁体   中英

AngularJS : Return a promise which is constructed from the result of another promise in angular?

I have the following function defined in a service, in which I use $http to get some data and set some of the 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 until now I've used a promise with the $http service but I don't know how to wrap the function with $q so that I can ultimately use it in the following manner:

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

I've searched for tutorials on angular promises but most of them simply explain what a promise is or do something similar to what I already did, I'm guessing what I want to do is possible but I can't find the right syntax or the right tutorial.

Just put return in front of the $http.get(...).then(...) chain, ie

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

This will ensure that the result of getComplexObject is a promise that will (when its resolved) contain the value of complexObject .

That is exactly what .then is designed for - it takes the promise from $http.get() and returns a new promise that will ultimately be resolved with its own return value instead of the original one.

FWIW, I'd put the declaration of complexObject inside the .then call - there's no need for it to be in the outer scope and it'll inadvertently cause a closure over that variable.

NB: Also, be careful about using this in your final callback - it may not be what you think it is!

You could return a promise and resolve 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;
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM