【发布时间】:2019-12-14 00:40:03
【问题描述】:
我想从该站点https://swapi.co/ 获取某些数据。 我使用 Promises 获取有关行星的数据,然后在某个行星对象内拍摄电影。之后,我需要在电影数组中的物种数组中获取数据。到目前为止一切正常。
我获取信息的代码:
const task = planetId => {
const url = `https://swapi.co/api/planets/${planetId}/`;
const getPlanet = () => { // getting 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) { // getting 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 => { // trying to get the 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)})
});
});
};
最后一行在控制台中显示为[Array[5], Array[20], Array[9]],数组中的每个元素为Promise {<pending>}。
我应该在代码中更改什么来获取所有物种对象并返回最终结果 - 一个带有电影和电影中物种的获取数据的星球?
【问题讨论】:
标签: javascript promise