Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
How do you fetch multiple pages of data into an array?

Here is my code

let url;
let planetCount;
let planetData = [];

//turn through the pages
for (let p = 1; p < 7; p++) {
  url = `https://swapi.boom.dev/api/planets?page=${p}`;

  //fetch data
  for (let j = 0; j < 1; j++) {
    fetch(url).then(res => res.json())
      .then(data => {

        //push data to array
        for (let i = 0; i < data.results.length; i++) {
          planetData.push(data.results[i]);
        }
      })

    console.log(planetData)

  }
}

And here is the output: https://i.stack.imgur.com/Hivwr.png

Problem: How do I make it so it all goes into one array, instead of 6?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You do have only one array. You just get an output six times because you run console.log() within a loop.

I expanded your code with the proper way to handle several async calls and wait until they are all finished:

let url;
let planetCount;
let planetData = []
let promises = [];

//turn through the pages
for (let p = 1; p < 7; p++) {
url = `https://swapi.boom.dev/api/planets?page=${p}`;

//fetch data
for (let j = 0; j < 1; j++) {
    promises.push(fetch(url).then(res => res.json())
        .then(data => {

            //push data to array
            for (let i = 0; i < data.results.length; i++) {
                planetData = planetData.concat(data.results[i]);
            }

        }));
    }
}

Promise.all(promises)
.then(() => {
    console.log(planetData.length, '=>', planetData);
})

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use async/await and Promise.all() to return an array of the pages returned. Once we have this, we can use Array.flat() to create a contiguous array of planet data:

async function getPlanets() {
    const urls = Array.from( { length: 7 }, (v,i) => `https://swapi.boom.dev/api/planets?page=${i + 1}` );
    const promises = urls.map(url => fetch(url).then(res => res.json()).then(data => data.results));
    const planetData = (await Promise.all(promises)).flat();
    console.log(`Results for ${planetData.length} planets downloaded...`);
    console.log('Results:', planetData);
}

getPlanets()

about 4 years ago · Juan Pablo Isaza Relatório

0

Does this answer your question? How can I fetch an array of URLs with Promise.all?

Promise all should be the right tool for you to use so that you wait until all promises are resolved before handling responses

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda