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

113
Views
Obtener 'indefinido' de la respuesta asincrónica a pesar de 'esperar' y 'entonces'

Estoy tratando de enviar una solicitud GET , analizar su respuesta y devolverla a otro método. Aparentemente tengo problemas para manejar la respuesta asíncrona.

Quiero usar los módulos estándar de Node.js, así que no Axios.

 // class 1: Calling API, processing and returning the response export async function getData() { let str = ''; const options = { hostname: 'jsonplaceholder.typicode.com', path: '/posts/', method: 'GET', json: true, }; https .get(options, response => { response.on('data', chunk => { str += chunk; }); response.on('end', () => { return parseJson(str); }); }) .on('error', error => { console.log(error); }); } async function parseJson(str) { const json = JSON.parse(str); var text; try { json.forEach(element => { text += element.body; }); // console.log(text); // I'm getting the expected output return text; } catch (error) { console.log('error'); } } // class 2: Calling the 2 methods above getData().then(function (value) { console.log('DATA: ' + value); // this is called first });

Desafortunadamente, como resultado obtengo un undefined . A pesar de usar async y then :

 DATA: undefined
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Cambie getData de la siguiente manera

 export function getData() { return new Promise((resolve, reject) => { let str = ''; const options = { hostname: 'jsonplaceholder.typicode.com', path: '/posts/', method: 'GET', json: true, }; https.get(options, response => { response.on('data', chunk => { str += chunk; }); response.on('end', () => { try { const result = parseJson(str); resolve(result); } catch (error) { reject(error); } }); response.on('error', reject); }) .on('error', reject); }); }

Ahora devuelve una Promesa, que se resuelve en el resultado de parseJson(str) o se rechaza con el error en on('error'

Y parseJson de la siguiente manera: no necesita ser async ya que no hay nada asíncrono en el código que contiene

Además, la eliminación de try/catch en parseJson y el uso de try/catch en .on("end" significa que puede rechazar la promesa devuelta por getData si hay un error en la llamada parseJson

 function parseJson(str) { const json = JSON.parse(str); let text = ''; json.forEach(element => { text += element.body; }); return text; }

alternativamente (en mi humilde opinión mejor)

 function parseJson(str) { const data = JSON.parse(str); // call it data, not json return data.map(({body}) => body).join(''); }

o incluso

 const parseJson = (str) => JSON.parse(str).map(({body}) => body).join('');

Pero eso no es importante :v

about 4 years ago · Juan Pablo Isaza Report

0

No devolviste nada en getData . Prueba esto

 export async function getData() { let str = ''; const options = { hostname: 'jsonplaceholder.typicode.com', path: '/posts/', method: 'GET', json: true, }; return https .get(options, response => { response.on('data', chunk => { str += chunk; }); response.on('end', () => { return parseJson(str); }); }) .on('error', error => { console.log(error); }); }
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!