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

200
Views
Nodejs espera hasta que se complete la función asíncrona e imprime los resultados

Quiero esperar a que se complete la solicitud HTTP POST y luego devolver la respuesta a la función de la persona que llama. Obtengo Indefinido cuando imprimo los resultados recibidos.

He definido el método de publicación de la siguiente manera:

 // httpFile.js const axios = require('axios'); module.exports = { getPostResult: async function(params) { console.log("getPostResult async called..."); var result = await axios.post("https://post.some.url", params) .then ((response) => { console.log("getPostResult async success"); return {response.data.param}; }) .catch ((error) => { console.log("getPostResult async failed"); return {error.response.data.param}; }); } }

Y lo estoy llamando de esta manera:

 // someFile.js const httpFile = require('./httpFile'); // Called on some ext. event async function getPostResult() { var params = {var: 1}; var result = await httpFile.getPostResult(params); // Getting Undefined console.log("Done Result: " + JSON.stringify(result)); }

No quiero manejar .then y .catch en la función de llamada, ya que quiero devolver los diferentes valores según el resultado POST.

¿Cómo debo esperar la respuesta y obtener los resultados de retorno?
En el código anterior, obtengo las declaraciones de registro como se esperaba y el "Resultado terminado" se imprime al final después de que regresa 'getPostResult'.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

está utilizando tanto await como . .then es por eso que devuelve indefinido.

así es como debería verse

 // httpFile.js const axios = require('axios') module.exports = { getPostResult: async function (params) { try { const res = await axios.post('https://post.some.url', params) return res.data } catch (error) { // I wouldn't recommend catching error, // since there is no way to distinguish between response & error return error.response.data } }, }

si desea detectar un error fuera de esta función, este es el camino a seguir.

 getPostResult: async function (params) { const res = await axios.post('https://post.some.url', params) return res.data },
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!