im learning promises for the school and there a lot of things that i dont understand
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
}
What i want to do:
its a async function that when you pass a name you get the name of the companions that share a episode with the name used, my problem is that the first .then works like i want, i get the episodes where the character take part, but the second fetchAll dont work, and i dont know why, the idea is that the second fetchAll get the data of each character in friends2
i think my code is a mess, but im starting to learn promises, sorry if the code its horrible
.then((body) => {
const [index] = body.results;
const ceo = index.episode
let friends = [];
friends.push(ceo);
return fetchAll(friends);
})
Do this change and it should work. fetchAll() is a asynchronous function which returns promise, either you need to put await before it or just directly return it because anyway you are not using that characters constant.