Necesito encadenar algunas solicitudes de API de la API de Google Maps y estoy tratando de hacerlo con Axios.
Aquí está la primera solicitud, que está en componentWillMount()
axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p1) .then(response => this.setState({ p1Location: response.data })) }Aquí está la segunda petición:
axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p2) .then(response => this.setState({ p2Location: response.data }))Luego tenemos una tercera solicitud, que depende de que se completen las dos primeras:
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 }))¿Cómo puedo encadenar estas tres llamadas para que la tercera suceda después de las dos primeras?
En primer lugar, no estoy seguro de querer hacer esto en su componentWillMount , es mejor tenerlo en componentDidMount y tener algunos estados predeterminados que se actualizarán una vez que se completen estas solicitudes. En segundo lugar, desea limitar la cantidad de setStates que escribe porque pueden causar re-renderizaciones adicionales, aquí hay una solución usando 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, }); }Un poco tarde para la fiesta, pero me gusta este patrón de encadenar promesas, devolviéndolas para mantener viva la cadena de promesas.
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));¿Has usado axios.all? Puedes probar con algo similar:
axios.all([axios.get(`firstrequest`), axios.get(`secondrequest`), axios.get(`thirdrequest`)]) .then(axios.spread((firstResponse, secondResponse, thirdResponse) => { console.log(firstResponse.data,secondResponse.data, thirdResponse.data); })) .catch(error => console.log(error)); Esto tomará todo su get y lo colocará dentro de una respuesta que debe llamarse con .data como: firstResponse.data