Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

javascript - 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);
})
question from:https://stackoverflow.com/questions/65926734/how-to-create-a-loop-of-get-calls-axios-through-a-list-and-return-the-answer-o

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...