I'm a bit new to JSON and Deferrers, so apologies it the answer is obvious.
I am working with the pokeapi.co and I am trying to pull out details of various pokemon using getJSON. I created a function which takes an array of URLs, runs a getJSON function to pull the data from the URLs, iterate over the data and push it into an array. I am trying to use the defer object and promises to determine when all that has been done so I can use the data in another function. Unfortunately, I seem to be doing something wrong.
var url = [
"http://pokeapi.co/api/v2/pokemon/1/",
"http://pokeapi.co/api/v2/pokemon/2/"
];
function getPokemonDetails(url){
var def = $.Deferred();
var promises = [];
var pokemon;
$.each(url, function(i, index){
var deferred = $.Deferred();
$.getJSON(index, function(data){
pokemon = [data.name, data.stats];
var abilityURLs = [];
$.each(data.abilities, function(a, abilities){
abilityURLs.push(abilities.ability.url)
});
pokemon.push(abilityURLs);
deferred.resolve(pokemon);
}); //End getJSON
deferred.done(function(data){
promises.push(data);
console.log(promises);
})// End Deferred
}); //End Each
$.when(...promises).done(function(){
console.log(arguments.length);
});
}
getPokemonDetails(url);
At the moment, when the console.log runs, I am expecting the length of the promises array to be 2, but at the moment it returns 0. I am not sure exactly where I went wrong.