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()
For better performance and cleaner code:
1. Use promise.all() or axios.all() to execute request1 and request2 at the same time. So request2 will execute without waiting for request1 response. After request1 and request2 return the response, request3 will continue execute based on the returned response data as parameter.
2. Template Strings use back-ticks (``)
async componentDidMount(){
try{
const [request1, request2] = 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}`)
]);
const request3 = await axios.get(`https://maps.googleapis.com/maps/api/directions/json?origin=place_id:${request1.data.results.place_id}&destination=place_id:${request2.data.results.place_id}&key=${API-KEY-HIDDEN}`);
console.log(request3);
}
catch(err){
console.log(err)
}
}