Hey campers,
I’m using the pokemon API but facing some issues.
so just before the code snippet, a promise was resolved, passing an array of pokemon objects (containing two properties - their name and URL).
for each pokemon in the array, I’d like to make an ajax request using the fetch API to return some data and push that into a new array.
once I’ve received all of that information I’d like to resolve the promise passing the new array of data which I then manipulate further (in the next .then() method)
I’ve managed to achieve all this using a promise nested within a promise, but it’s a messy solution. Does anyone have any ideas on a cleaner way to achieve the same thing, it’d be much appreciated?
thank you.
.then(pokemon_arr => {
console.log('pokemon are: ', pokemon_arr);
let output = `<div class='card-columns my-3'>`;
return new Promise(function(resolve, reject) {
let counter = 0;
for (let pokemon of pokemon_arr) {
fetch(`${pokemon.url}`)
.then(res => res.json())
.then(pokemon => {
return new Promise (function (resolve, reject) {
let dbl_damages_to_arr = [];
pokemon.types.forEach(type => {
fetch(`https://cors.io/?http://pokeapi.co/api/v2/type/${type.type.name}`)
.then(res => res.json())
.then(data => {
data = data.damage_relations.double_damage_to;
if (!dbl_damages_to_arr.includes(data))
dbl_damages_to_arr.push(data);
if (dbl_damages_to_arr.length == pokemon.types.length) {
document.getElementById('output').innerHTML += `<p class='text-center'>..almost there</p>`;
dbl_damages_to_arr = dbl_damages_to_arr.reduce((a,b) => a.concat(b)); // flatten the array
resolve({dbl_damages_to_arr, pokemon})
}
})
.catch(err => {
handleError(err);
reject(err)
})
})
})
})