Nodejs等待async函数完成并打印结果



我想等待HTTPPOST请求完成,然后向调用方函数返回响应。当我打印收到的结果时,我得到了未定义。

我已经定义后的方法如下:

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

我这样称呼它:

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

我不想在调用函数中处理.then.catch,因为我想根据POST结果返回不同的值。

我应该如何等待响应并获得返回结果
在上面的代码中,我得到了预期的日志语句;完成结果";在"getPostResult"返回后的最后打印。

您同时使用await&.then就是它返回undefined的原因。

应该是这样的

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

如果您想捕捉这个函数之外的错误,那么这就是方法。

getPostResult: async function (params) {
const res = await axios.post('https://post.some.url', params)
return res.data
},

最新更新