Skip to content
Advertisement

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.

Advertisement

Answer

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
  },
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement