【问题标题】:Axios: Chain multiple requests using data of one request in anotherAxios:使用另一个请求中的数据链接多个请求
【发布时间】:2020-07-15 08:06:12
【问题描述】:

我需要进行一堆 API 调用并最终像这样组合它们的数据

axios.all([
  axios.get('https://api.github.com/users/mapbox'),
  axios.get('https://api.github.com/users/phantomjs')
])
.then(responseArr => {
  //this will be executed only when all requests are complete
  console.log('Date created: ', responseArr[0].data.created_at);
  console.log('Date created: ', responseArr[1].data.created_at);
});

但我也想在另一个 API 调用中使用在一个 API 中接收到的数据。有点像

data = axios.get('https://api.github.com/users/mapbox'),
axios.get('https://api.github.com/users/'+data.user);

如何将它用于 5 个 API 调用?

【问题讨论】:

  • 使用await 或嵌套.then() 对调用进行排序,如图here

标签: node.js express axios


【解决方案1】:

我将为此使用 async-await。

async function fetchData(){
try {
 const response = await axios.get("https://api.github.com/users/mapbox");
 const res = response.data;
 const getUser = await axios.get(`https://api.github.com/users/${res.user}`);
 const getWhatever = getUser.data;
 ......
 ......
 } catch (error) {
 console.log(error)
 }
}

您也可以在获得结果时使用嵌套的 .then 方法,然后使用该方法发出另一个请求。但我认为 async-await 更好。

【讨论】:

    猜你喜欢
    • 2017-10-26
    • 2021-01-10
    • 2021-06-21
    • 2018-06-05
    • 1970-01-01
    • 2017-06-17
    • 2019-12-25
    • 2021-11-23
    • 2015-04-22
    相关资源
    最近更新 更多