【发布时间】:2018-05-12 04:35:32
【问题描述】:
我正在测试等待函数,但是当我检查异步函数的返回时,我有一个“未定义”的结果,我的 express 函数是这样的(我删除了不必要的代码,只是为了展示我是如何使用异步的
p>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)
});
};
【问题讨论】:
-
await仅在函数调用返回与异步选项完成相关联的承诺时才真正等待异步操作。restClient.get()似乎不是这种情况,因为您正在向它传递一个完成回调。因此,您的代码不会await该结果。另外,您不能在回调中await调用者也不期望返回承诺。所以,你在回调中的await也不会做你想做的事。 -
不要混合常规回调和承诺。将所有异步操作转换为使用 Promise,然后并且只有这样你才能简单地使用 async/await。
-
感谢@jfriend00,所以修复应该是使用支持承诺的休息客户端?
-
这将是一个开始。您还必须了解
async函数如何返回一个通过其返回值实现的承诺,以及await如何需要等待承诺才能正确使用它们。 -
你需要从
getAppsConsumptionSum返回一些东西才能从await getAppsConsumptionSum(variable1, startPeriod, endPeriod)得到一些东西
标签: node.js async-await