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

126
Views
Pasar un valor de una solicitud a otra solicitud en ReactJs

Necesito ayuda porque no pude usar una función separada para generar el token: da una promesa, no un valor. Me dijeron que un valor solo se puede usar dentro de una función.

Para cada solicitud, genero un nuevo token en la primera solicitud y luego paso ese token a la segunda solicitud.

Intenté crear una función separada para generar el token, pero la búsqueda devuelve una promesa.

Como resultado, hice una función tan grande y funciona. ¿Hay alguna manera de hacer una función separada para la primera solicitud y pasar el resultado a la segunda solicitud?

La primera función de generación de tokens se requiere con frecuencia, mientras que la segunda solicitud siempre es diferente.

 fetch('/api/token', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ 'id': '5' }), }) .then(response => response.json()) .then(result => { fetch('/api/reviews', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + result.token, }, body: JSON.stringify({ 'limit': 10 }), }) .then(response => response.json()) .then(result => { this.setState({ data: result.data }); }) })
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

crear una función que devuelva la promesa

 async function getToken() { return await fetch('/api/token', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ 'id': '5' }), }) .then(response => response.json()) .then(result => { return Promise.resolve(result.token); }).catch(error => { return Promise.reject(error); }) } async function getReview() { const token = await getToken().then(token => { return token }).catch(error => { //handle error }); fetch('/api/reviews', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token, }, body: JSON.stringify({ 'limit': 10 }), }) .then(response => response.json()) .then(result => { this.setState({ data: result.data }); }) }

no probé este código pero entiendes la idea

probaré y actualizaré mi respuesta lo antes posible

about 4 years ago · Juan Pablo Isaza Report

0

Sí, puedes con async / await . Le permitirá elevar el alcance léxico de la respuesta de la API desde el interior del " .then de devolución de llamada" y al alcance de la función principal.

Su función separada que obtiene el token devolverá una promesa, pero luego la función solicitante esperará a que la promesa se ejecute y resuelva antes de continuar.

 async function fetchToken() { const response = await fetch('/api/token', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ 'id': '5' }), }) return await response.json(); } async function getReviews() { const response = await fetch('/api/reviews', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + result.token, }, body: JSON.stringify({ 'limit': 10 }), }) const result = await response.json(); this.setState({ data: result.data }); }

Además, si no es necesario realizar la llamada de token cada vez que se realiza la llamada de revisión, puede memorizar el valor y utilizar ese valor memorizado.

 const tokenMemo = useMemo(async () => await getToken(), []); async function getReviews() { const response = await fetch('/api/reviews', { // ... 'Authorization': 'Bearer ' + tokenMemo, // ... }
about 4 years ago · Juan Pablo Isaza 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!