So I realize I have a scoping problem going on here. I'm hitting an API to return a list of films. The response includes an array of film objects. Each film object has an array of characters, but each character is just an endpoint. The goal is to list each film with the first 3 characters associated with that particular film. What is going to be the most efficient way to accomplish this? Here is the code I currently have, which I know is wrong, but should convey what I'm trying to do fairly clearly.
import {getCharByUrl, getFilms} from './api/swapiApi';
getFilms().then(result => {
let films = result.results; // Array of films
let episodes = ``;
films.forEach(film => {
let urls = film.characters; // Array of endpoints to hit
let chars = `<ul>`;
for (let i = 0; i < 3; i++) {
getCharByUrl(urls[i]).then(character => {
chars += `<li>${character.name}</li>`;
});
}
chars += `</ul>`;
episodes += `
<div class="col-sm-4">
<div>${film.title}</div>
<div>${film.director}</div>
${chars}
<hr>
</div>
`;
});
global.document.getElementById('films').innerHTML = episodes;
});
Code that worked for me:
import {getCharByUrl, getFilms} from './api/swapiApi';
getFilms().then((result) => {
let films = result.results; // Array of films
let episodes = ``;
var Promise = require('es6-promise').Promise;
films.forEach((film) => {
let urls = []; // Array of endpoints to hit
for(let i = 0; i < 3; i++) {
urls.push(film.characters[i]);
}
let chars = `<ul class="list-unstyled">`;
Promise.all(urls.map((url) => {
return getCharByUrl(url);
})).then((data) => {
// data will be an array of the responses from all getCharByUrl requests
data.forEach((character) => {
chars += `<li>${character.name}</li>`;
});
chars += `</ul>`;
}).then(() => {
episodes += `
<div class="col-sm-4">
<div>${film.title}</div>
<div>${film.director}</div>
${chars}
<hr>
</div>
`;
global.document.getElementById('films').innerHTML = episodes;
});
});
});