I am looking to extract specific information from the following website . I have implemented Promises in order to retrieve data about planets, then films associated with a particular planet object. My next goal is to access data within the species array nested inside the films array. So far, everything is functioning correctly up to this stage.
Below is my code for fetching the necessary information:
const task = planetId => {
const url = `https://swapi.co/api/planets/${planetId}/`;
const getPlanet = () => { // retrieving the planet by its Id
return new Promise(function(resolve, reject) {
https
.get(`${url}`, function(res) {
res.on("data", function(d) {
const planetData = JSON.parse(d.toString());
resolve(planetData);
});
})
.on("error", function(e) {
reject(e);
console.error(e);
});
});
};
getPlanet().then(gotPlanet => {
const planet = gotPlanet;
const filmsArray = planet.films;
const filmsArrayUrl = filmsArray.map(it => {
return new Promise(function(resolve, reject) { // retrieving films array
https
.get(it, function(res) {
res.on("data", function(d) {
const films = JSON.parse(d.toString());
resolve(films);
});
})
.on("error", function(e) {
reject(e);
console.error(e);
});
});
});
Promise.all(filmsArrayUrl).then(gotFilms => {
const filmsNew = gotFilms;
planet.films = filmsNew;
const speciesArray = planet.films.map(it => it.species);
const speciesArrayUrl = speciesArray.map(it => it.map(el => { // attempting to retrieve species data
return new Promise(function(resolve, reject) {
https.get(el, function(res) {
res.on('data', function(d) {
const speciesFetched = JSON.parse(d.toString())
resolve(speciesFetched)
})
}).on('error', function(e) {
reject(e)
console.error(e)
})
})
}))
Promise.all(speciesArrayUrl).then(species => {console.log(species)})
});
});
};
The final line displayed in the console shows as [Array[5], Array[20], Array[9]]
, where each element within the array appears as Promise {<pending>}
.
What modifications should be made to the code to properly fetch all species objects and present the end result - a planet containing the retrieved information on films and species within those films?