Home > Blockchain >  How can I get one response for different API pages
How can I get one response for different API pages

Time:05-26

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)
  };

CodePudding user response:

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.

CodePudding user response:

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/

CodePudding user response:

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);
  • Related