Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

371
Views
Axios: encadenar varias solicitudes de API

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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, }); }
over 4 years ago · Santiago Trujillo Report

0

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));
over 4 years ago · Santiago Trujillo Report

0

¿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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!