Skip to content
Advertisement

fetching multiple urls from an api

Basically I am working with a star wars API called swapi (i haven’t worked with APIs before) and I am fetching the data with a simple async-await function.

My goal is to get all the movies that API holds (a total of 6 of them) I am using a template tag in HTML and I’m cloning it in javascript and then displaying all 6 movies.

So to clarify, I am getting an array of 6 objects that I’m displaying the title of each movie in HTML without a problem since the title is in a string format, but every object has also a key (characters) that has a value of an array and inside that array is a big list of characters that play in the movie but they are in a URL format (http://swapi.dev/api/people/1/) except the last number in the URL changes for each of them.

Is there a smart way to fetch and display all the character names for each movie they have played in? because all the ways I’m trying aren’t working. The ideal solution would be to display all the characters that have played in each movie and having the possibility to click on them and seeing a few details that they hold.

console log of movies object

Advertisement

Answer

so this is my guess (I have no time to test this second, but will shortly and get this answer working don’t pass.)

async function getSWdata(){
await fetch('starwars api')
.then(res=>res.json())
.then(data=>data.people.map(async (x)=>await fetch(x).then(res=>res.json())));
}

the things I’m unsure about are the exact syntax of async => functions, or any complications of async functions nested inside an async function… but this might get you on the right track regardless.

EDIT::: this below is working mostly for me (I am iffy sure on promises => there are improvements to be made)

async function getSWdata(){
    return  await fetch('https://swapi.dev/api/films')
    .then(res=>res.json())
    .then(data=>
        {      
        const r = data.results.map((results)=>
            {
            const toons = results.characters.map(async (toon)=>await fetch(toon).then(res=>res.json()))
            results.characters = toons;
            return results;
            })
            data.results = r;
           return data; 
    });
    }
const SWData = getSWdata();
console.log(SWData);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement