Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
Nodejs wait till async function completes and print the results

I want to wait on the HTTP POST request to complete and then return response to the caller function. I am getting Undefined when I print the received results.

I have defined post method as below:

// 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};
        });
    }
}

And I am calling it in this way:

// 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)); 
}

I don't want to handle the .then and .catch in the calling function as I want to return the different values based on the POST result.

How should I wait for the response and get the return results.
In the above code I am getting the log statements as expected and "Done Result" get printed at the very end after the 'getPostResult' returns.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

you are using both await & .then thats why it returns undefined.

this is how it should look

// 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
    }
  },
}

if you want to catch error outside of this function then this is way to go.

 getPostResult: async function (params) {
      const res = await axios.post('https://post.some.url', params)
      return res.data
  },
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda