Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

319
Vistas
JavaScript Use Variable Defined in Then Outside of Then

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;
        });
    });
});
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I'd take a look at Promise.all: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all. Not positive without seeing the api responses but I think you could do something like this:

    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>`;

            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;
            });
        });
    });
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda