1

I'm tapping into an API that uses JSONP using AngularJS. I'm trying to format the JSON that is returned from my factory but am unable to access it using defer.promise. I'm able to see the returned data in the browser, just not in the console.

Which way is better? What is the difference between $promise.then and defer.promise?

defer.promise

var defer = $q.defer();
defer.promise.then(function () {
    pet.details = BattlePetsFactory.query({
        SpeciesID: 258
    });

    // Returns e { $promise={...}, $resolved=false, toJSON=function(), more...} in the console
    console.log(pet.details);

    // Returns undefined
    console.log(pet.details.name);
});

defer.resolve();

Why doesn't this return Mini Thor like $promise.then?

$promise.then

var factory = BattlePetsFactory.query({
    SpeciesID: 258
});

factory.$promise.then(function (data) {
    pet.details = data;

    // Returns Mini Thor 
    console.log(pet.details.name);
});

The reason for me needing to access the data in the code is because I am modifying the json structure so I can store the values in my DB.

Here is my factory, just in case it's needed.

app.factory('BattlePetsFactory', ['$resource', function ($resource) {
    return $resource('https://us.api.battle.net/wow/battlePet/species/:SpeciesID' + queryString, {}, {
        query: {
            method: 'JSONP',
            params: {
                jsonp: 'JSON_CALLBACK'
            }
        }
    });
}]);
  • 2
    Just chain through the already available promise rather than using a deferred patter. http://stackoverflow.com/questions/23803743/what-is-the-deferred-antipattern-and-how-do-i-avoid-it – PSL Feb 02 '15 at 21:52
  • I'm not sure how to chain through the already available promise. Why wouldn't pet.details.name give me the data since name is in the root of the result? – Joshua Christensen Feb 02 '15 at 22:16

0 Answers0