【发布时间】:2020-01-17 09:59:24
【问题描述】:
我多年来一直坚持做这个练习,我终于认输并寻求帮助。
对星球大战 API [https://swapi.co/] 进行 AJAX 调用,并获取该系列中每部电影的开场抓取。完成此操作后,循环遍历每部电影的行星数组,并进行更多 AJAX 调用以收集按电影组织的每个行星的名称。然后,控制台记录一组对象,其中每个对象都包含特定电影的开场爬行,以及该电影中出现的每个行星的名称。
我已经阅读了一些关于异步 js 的文章并观看了一些视频,我“认为?”,我有点明白了。不过这真的不想工作。
var promiseList = [];
var fetchArray = function(arr) {
promiseArr = arr
.map(url => fetch(url)
.then(res => res.json())
.then(planet => planet.name)
);
Promise.all(promiseArr)
.then(data => console.log(data));
}
// fetchArray doesn't work at all. Curious if it's possible to run this code as it's technicall synchronous (idk).
for (let number = 1; number < 8; number ++) {
var t = fetch(`https://swapi.co/api/films/${number}/`)
.then(res => res.json())
promiseList.push(t)
}
console.log("NAHANH", promiseList)
// Prints out [[object Promise] { ... }, [object Promise] { ... }, [object Promise] { ... }, [object Promise] { ... },
[object Promise] { ... }, [object Promise] { ... }, [object Promise] { ... }]
Promise.all(promiseList)
.then(films => films.map(film => ({
"title": film.title,
"planets": film.planets,
"opening_crawl": film.opening_crawl,
})))
// Works up untill this point, this next then doesn't work, my aim is to alter the film.plants property in every
array object and actually fetch the planet rather than just the url!
// An example print out would be...
// {
// opening_crawl: "Luke Skywalker has vanis...",
// planets: ["https://swapi.co/api/planets/61/"],
// title: "The Force Awakens"
// }]
.then(films => films.map(film => {
film.planets = film.planets
.map(url => fetch(url)
.then(res => res.json())
.then(planet => planet.name)
.catch(error => console.log(error.message))
);
}
.then(data => console.log(data))
// Which would then finally resolve to (this is what I want but cannot get at the moment!)
// {
// opening_crawl: "Luke Skywalker has vanis...",
// planets: ["Yavin IV"],
// title: "The Force Awakens"
// }]
它几乎可以返回一个对象。提取数组根本不起作用。并且我尝试检索行星名称的第二次更改不起作用。
【问题讨论】:
-
你读过这本吗? api.jquery.com/jquery.get
标签: javascript ajax promise fetch