Axios: chaining multiple API requests

前端 未结 7 742
失恋的感觉
失恋的感觉 2020-12-07 14:15

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

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

相关标签:
7条回答
  • 2020-12-07 14:46

    A little late to the party, but I like this pattern of chaining promises, returning them to keep the promise chain alive.

    axios
      .get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p1)
      .then(response => {
        this.setState({ p1Location: response.data });
        return axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p2);
      })
      .then(response => {
        this.setState({ p2Location: response.data });
        return axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p3);
      })
      .then(response => {
        this.setState({ p3Location: response.data });
      }).catch(error => console.log(error.response));
    
    0 讨论(0)
提交回复
热议问题