Search code examples
javascriptlistgetaxiosfunc

How to create a loop of get calls (axios) through a list and return the answer of all


How to create a loop of get calls through a list and return the answer of all.

const axios = require('axios');
const id = ['234','9887']
axios.get(`https://myapi/api/id/${id}`, {
method: 'GET',
headers:{'xxxxxxxxxx': 'xxxxxxxxxxx',
}})

      .then(function (response = response.json()) {
// handle success
console.log = (response.data)
     })
.catch(function (error) {
// handle error
console.log(error);
})

Solution

  • I think this what you are looking for.

    I have changed your fake API for a real one, so you can test.

    const axios = require('axios');
    const id = ['234','9887']
    
    const promArr = id.map(
      id =>
        axios.get(
          `https://postman-echo.com/get?key=${1234}`, 
          {
            method: 'GET',
            headers:{'xxxxxxxxxx': 'xxxxxxxxxxx',}
          }
        )
    )
    
    Promise.all(promArr)
      .then(function (responses) {
        // handle success
        responses.map(response => console.log(response.data))
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })