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

193
Views
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 answers
Answer question

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 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!