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

173
Visualizações
How can I get one response for different API pages

I'm trying to get one response from an API that has different pages URL, how can i achieve this in just one API call.

Here's my code

async function arrayFetcher (){
      // Get `urlArray` from object param
      let urlArray = [];
      let url = ""
      for(let i = 1; i < 20; i++) {
          url = `https://api.google.com/page=250&page=${i}&sparkline=false`
      }
      const resp =  await axios.get(url)
      const response = await urlArray?.Promise?.all(resp).then(res => res.json());
      console.log(response)
  };
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use Promise.all. Make an array (let's say urls) & then -

const results = await Promise.all(urls.map(async url => {
  const resp = await axios.get(url);
  return resp.json();
}));

Update: You also need to push the url into the urlArray

for(let i = 1; i < 20; i++) {
    url = `https://api.google.com/page=250&page=${i}&sparkline=false`;
    urlArray.push(url);
}

Then use it in Promise.all.

about 4 years ago · Juan Pablo Isaza Relatório

0

you can do this with Promise.all , an example could be:

const fetchData = async () => {
    const url1 = 'https://jsonplaceholder.typicode.com/todos/1'
    const url2 = 'https://jsonplaceholder.typicode.com/todos/2'
    const url3 = 'https://jsonplaceholder.typicode.com/todos/3'

    const result = await Promise.all([fetch(url1), fetch(url2), fetch(url3)])
    const dataArr = result.map(result => result.json())
    const allData = Promise.all(dataArr)
    return allData
}


fetchData().then(res => console.log(res))

https://jsfiddle.net/0gkhmcbp/

about 4 years ago · Juan Pablo Isaza Relatório

0

This won't result in one API call, rather the network will see one call per URL which is called by axios.get(url). To make one API call and get the same data would require additional parameters on the endpoint or a new endpoint; this is a server side change by the API owner.

Axios does not require response.json() as it already does that for you. The browser native Fetch API does require it, fetch(url).then(res => res.json()).then(data => console.log(data)).

async function arrayFetcher() {
  // generate 5 urls to fetch
  // API starts at 1 but index at 0, so `index+1` for valid URI
  const urls = [...Array(5).keys()].map((item, index) => `https://jsonplaceholder.typicode.com/todos/${index+1}`);

  // make API calls
  const results = await Promise.all(urls.map(async url => await axios.get(url)));

  // display each result
  // Axios places the value in `data` property
  results.forEach(result => console.log(result.data));
}

arrayFetcher();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js"></script>

You could potentially improve this code to separate the array generation from the fetcher function and pass in the array as an argument. Example:

async function arrayFetcher(urls) { /*...*/ }

function generateUrlArray(baseUrl, amount) {
  return [...Array(amount).keys()].map((item, index) => `${baseUrl}${index+1}`);
}

const urls = generateUrlArray('https://example.com/', 5); // generate array

arrayFetcher(urls);
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