Axios:链接多个 API 请求 [英] Axios: chaining multiple API requests

查看:34
本文介绍了Axios:链接多个 API 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要链接来自 Google Maps API 的一些 API 请求,我正在尝试使用 Axios 来实现.

I need to chain a few API requests from the Google Maps API, and I'm trying to do it with Axios.

这是第一个请求,在 componentWillMount()

Here is the first request, which is in componentWillMount()

axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p1)
  .then(response => this.setState({ p1Location: response.data }))  }

这是第二个请求:

axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p2)
  .then(response => this.setState({ p2Location: response.data }))

然后我们有第三个请求,它依赖于前两个请求的完成:

Then we have a third request, which is dependent on the first two being completed:

axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + this.state.p1Location.results.place_id + '&destination=place_id:' + this.state.p2Location.results.place_id + '&key=' + 'API-KEY-HIDDEN')
  .then(response => this.setState({ route: response.data }))

如何链接这三个调用,以便在前两个调用之后发生第三个调用?

How can I chain these three calls so that the third happens after the first two?

推荐答案

首先,不确定是否要在 componentWillMount 中执行此操作,最好将其放在 componentDidMount 并有一些默认状态,一旦完成这些请求就会更新.其次,你想限制你写的 setStates 的数量,因为它们可能会导致额外的重新渲染,这里是一个使用 async/await 的解决方案:

First off, not sure you want to do this in your componentWillMount, it's better to have it in componentDidMount and have some default states that will update once done with these requests. Second, you want to limit the number of setStates you write because they might cause additional re-renders, here is a solution using async/await:

async componentDidMount() {

  // Make first two requests
  const [firstResponse, secondResponse] = await Promise.all([
    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=${this.props.p1}`),
    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=${this.props.p2}`)
  ]);

  // Make third request using responses from the first two
  const thirdResponse = await axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + firstResponse.data.results.place_id + '&destination=place_id:' + secondResponse.data.results.place_id + '&key=' + 'API-KEY-HIDDEN');

  // Update state once with all 3 responses
  this.setState({
    p1Location: firstResponse.data,
    p2Location: secondResponse.data,
    route: thirdResponse.data,
  });

}

这篇关于Axios:链接多个 API 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆