【发布时间】:2022-02-01 18:22:41
【问题描述】:
我对学校的学习承诺还有很多我不明白的事情
async function getCompanion(name){
const response = await fetch("https://rickandmortyapi.com/api/character/?name=" + name)
if(response.status !== 200) throw `HTTP error: ${response.status}`;
const data = response.json()
return data
.then((body) => {
const [index] = body.results;
const ceo = index.episode
let friends = [];
friends.push(ceo);
return fetchAll(friends);
})
.then((body2) => {
const [index2] = body2;
const ceo2 = index2.characters
let friends2 = [];
friends2.push(ceo2);
//console.log(friends2)
return fetchAll(friends2)
}).then((body3) =>{
console.log(body3);
})
.catch( (error) => {
console.log(`Error: ${error}`)
})
}
async function fetchAll(urls){
const res = await Promise.all(urls.map(u => fetch(u)))
const jsons = await Promise.all(res.map(r => r.json()))
console.log(jsons)
return jsons
}
我想做什么:
它是一个异步函数,当你传递一个名字时,你会得到与所用名字共享一集的同伴的名字,我的问题是第一个 .then 像我想要的那样工作,我得到角色所在的剧集部分,但是第二个 fetchAll 不起作用,我不知道为什么,想法是第二个 fetchAll 获取friends2中每个角色的数据
我认为我的代码是一团糟,但我开始学习承诺,如果代码很糟糕,对不起
【问题讨论】:
-
await和.then()是替代语法。在任何给定的功能中,不要混合使用它们。
标签: javascript api promise fetch