node.js - 未定义的结果nodejs异步等待
问题描述
我正在测试等待函数但是当我检查异步函数的返回时我有一个“未定义”的结果,我的快速函数是这样的(我删除了不必要的代码,只是为了展示我如何使用异步
const getAppsConsumptionSum = async (msisdn, startPeriod, endPeriod) => {
var urlTigoPlus = 'http://...';
var args = {
requestConfig: {
timeout: config.get('localServer.remoteTimeout')
}
};
remoteApi = await restClient.get(url, args,
async (data, response) => {
if (response.statusCode === 200) {
sumatoria = await group(data.arrayofdata).by('subapplication').reduce(async function(id, entries) {
return {
appname: id,
mb: (entries.map(getBytes).reduce(add)) / 1048576
};
});
return sumatoria;
} else {
next(utils.error(503));
}
}
);
};
exports.dataAppsConsumption = async function(req, resp, next) {
let prepaidQuery = 'select ...';
const resultPrepaid = await clientDseDev.execute(prepaidQuery)
.then(async resultPrepaid => {
sumatoria = await getAppsConsumptionSum(variable1, startPeriod, endPeriod);
console.log('this variable shows undefined ' + sumatoria)
//i tried also with this
getAppsConsumptionSum(variable1, startPeriod, endPeriod).then((sumatoria) => {
console.log('this variable shows undefined ' + sumatoria)
});
})
.catch((err) => {
console.log(err)
});
};
解决方案
感谢大家的帮助,@jfriend00 解决方案是正确的,我还必须在调用 axios 函数之前添加一个 return
return axios.get(url, options
)
.then(async function (response) {
if (response.status === 200){
group(response.data.arrayofdata).by('subapplication').reduce(function(id, entries) {
return {
appname: id,
mb: (entries.map(getBytes).reduce(add)) / 1048576
};
});
return sumatoria;
推荐阅读
- coldfusion - 为什么使用定义 CFC 目录路径的 CF 管理员映射无法使用指向组件的点符号路径的 CreateObject?
- sql - 如何使用 SQL 执行此搜索?
- c# - 如何在 .Net Core MVC 中为 Azure SignalR 调用 CosmosDBTrigger 和 HttpResponseMessage?
- javascript - 在 PREM Dynamics CRM 2016 JavaScript 上相当于我的 C# QueryExpression
- typo3 - 如何通过 Typoscript 正确实例化 tx_news
- php - 打印特定数组数据时出现问题
- java - 使用 gradle 创建可执行 jar
- c# - 当另一个窗口关闭时需要更新一个窗口。需要再次实例化关闭的窗口
- html - 将用 Papaparse 解析的 CSV 渲染成 HTML
- r - 让动画滑块向后(从右到左)模拟倒计时?