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

163
Views
React Native obtiene el valor de retorno de la función asíncrona

Estoy tratando de obtener datos de ubicaciones de bares del servidor MYSQL y mi función de búsqueda funciona bien. Pero después de eso, este bloque try-catch no devuelve nada. También probé sin bloque try-catch pero no cambia nada

 getPubsFromDatabase = async () => { let response = await fetch(fetchDataUrl, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, }); try{ let json = await response.json(); console.log(json) return json; } catch (error) { console.log(error); } }

Y aquí, estoy tratando de obtener el valor de retorno de la función. Pero en esta versión, ni siquiera puedo ver ninguna salida de console.log. Lo que quiero decir con la versión es que, si pongo la segunda línea fuera del bloque asíncrono sin la palabra clave "esperar", puedo ver el archivo console.log pero me da "indefinido".

 (async () => { const locationsData = await getPubsFromDatabase(); console.log(locationsData) })()
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede usar then y catch en la función fetch .

 const getPubsFromDatabase = () => { return fetch(fetchDataUrl, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, }).then(async (response) => { const json = await response.json().then((data)=>{ return data; }).catch((err)=>{ console.log('error from json method: ',err); return { error: { message: 'error from json method', object: err }}; }); console.log(json); return json; }).catch((error) => { console.log('error from request: ', error); return { error: { message: 'error from request', object: error } }; }); }

Y cuando usas el método getPubsFromDatabase sería de la siguiente manera:

 (async () => { const locationsData = await getPubsFromDatabase(); console.log(locationsData); })()
about 4 years ago · Santiago Trujillo Report

0

Puede usar Promise para devolver un resultado o un error. En el ejemplo que se muestra a continuación, he usado la biblioteca axios, pero también puede intentar lo mismo con fetch api. Por ejemplo

 export const getData = () => { return new Promise((resolve, reject) => { const url = ApiConstant.BASE_URL + ApiConstant.ENDPOINT; const API_HEADER = { "Authorization": token, }; axios .get(url, { headers: API_HEADER, }) .then((res) => { resolve(res.data); }) .catch((error) => { // handle error reject(error); console.log(error); }); }) }

Puede llamar a la función anterior en un componente o pantalla como esta:

 getData().then( (data) => { } ).catch( error => { console.log(error) } )
about 4 years ago · Santiago Trujillo Report

0

Resolví el problema en lugar de devolver el valor de la función, establecí el valor dentro de la función. Esto parece funcionar ahora.

 const [locationsData, setLocationsData] = useState(); getPubsFromDatabase = async () => { let response = await fetch(fetchDataUrl, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, }); try{ let json = await response.json(); setLocationsData(json); // Here, I changed the value of the locationsData instead of returning } catch (error) { console.log(error); } }

Y para llamar a la función:

 useEffect(()=> { getPubsFromDatabase(); },[])
about 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!