【问题标题】:How to create a loop of get calls (axios) through a list and return the answer of all如何通过列表创建get调用(axios)循环并返回所有答案
【发布时间】:2021-01-27 20:17:54
【问题描述】:

如何通过列表创建一个 get 调用循环并返回所有的答案。

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

【问题讨论】:

    标签: javascript list get axios func


    【解决方案1】:

    我想这就是你要找的。​​p>

    我已将您的假 API 更改为真实的,因此您可以进行测试。

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

    【讨论】:

    • 谢谢马林。如果可能的话,另一个疑问。如何将通话之间的时间限制在一秒内?
    • 这并不像看起来那么简单......虽然,它是可能的。尝试自己实现一些东西,付出一些努力,如果你遇到困难,总是写一个问题来解释你卡在哪里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多