Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

316
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!