首页 > 解决方案 > 未定义的结果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)
    });
};

标签: node.jsasync-await

解决方案


感谢大家的帮助,@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;

推荐阅读