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:
JavaScript
x
19
19
1
// httpFile.js
2
const axios = require('axios');
3
4
module.exports = {
5
getPostResult: async function(params) {
6
console.log("getPostResult async called...");
7
var result = await axios.post("https://post.some.url", params)
8
.then ((response) => {
9
console.log("getPostResult async success");
10
return {response.data.param};
11
})
12
.catch ((error) => {
13
console.log("getPostResult async failed");
14
return {error.response.data.param};
15
});
16
}
17
}
18
19
And I am calling it in this way:
JavaScript
1
14
14
1
// someFile.js
2
const httpFile = require('./httpFile');
3
4
// Called on some ext. event
5
async function getPostResult() {
6
7
var params = {var: 1};
8
var result = await httpFile.getPostResult(params);
9
10
// Getting Undefined
11
console.log("Done Result: " + JSON.stringify(result));
12
}
13
14
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
JavaScript
1
17
17
1
// httpFile.js
2
const axios = require('axios')
3
4
module.exports = {
5
getPostResult: async function (params) {
6
try {
7
const res = await axios.post('https://post.some.url', params)
8
return res.data
9
} catch (error) {
10
// I wouldn't recommend catching error,
11
// since there is no way to distinguish between response & error
12
return error.response.data
13
}
14
},
15
}
16
17
if you want to catch error outside of this function then this is way to go.
JavaScript
1
5
1
getPostResult: async function (params) {
2
const res = await axios.post('https://post.some.url', params)
3
return res.data
4
},
5