节点js在嵌套循环中处理等待

时间:2017-08-21 06:37:09

标签: node.js asynchronous async-await

如何在嵌套循环中处理多个async/await

这是我的代码:

export default async (req) => {
  const report = req.body.webAudits;
  const def = deferred();

  if(report.length == 0) return []; 
  var reportList = [];
  for(const item of report.entries()) {
    for(const [runIndex, run] of item.runs.entries()) {
      const result = await waComplianceBusiness(req, run.id);
      var failureList = [];
      if (!result.data.overviews) {
        continue;
      }
      const compliance = result.data.overviews[0].compliance;
      if(!compliance) {
        continue;
      }
      for(const rule of compliance.entries()) {
        const response = await waRuleOverview(req, run.id, rule.id);
        const { failedConditions, ruleName } = response.data;

        if(response.data.pagesFailed === 0) continue;
        for(let condition of failedConditions) {

          const request = {
            itemId: condition.conditionResult.id,
            itemType: condition.conditionResult.idType,
            parentId: condition.conditionResult.parentId,
            parentType: condition.conditionResult.parentType
          }
          const body = {
            runId: run.id,
            ruleId: rule.id,
            payload: request
          }
          const failure = await waConditionOverview(req, body);

          const description = failure.data.description;
          const conditionValues = failure.data.conditionValues;

          var valueList = [];

          conditionValues.forEach(item => {
            const value = (item.value == "") ? 'empty' : item.value;
            if(valueList.indexOf(value) == -1) {
              valueList.push(value);
            }
          })

          var actualValue = '';
          valueList.forEach((value, v => {
            actualValue += value;
            if(v > 0) {
              actualValue += '\n';
            }
          });

          var expected = description.expected[0] ? description.name + ' ' + description.matcher + ' ' + description.expected[0] : description.name + ' ' + description.matcher

          if(description.idType == "variable") {
            var failureObj = {
              ruleName: ruleName,
              expected: expected,
              actual: description.name + '=' + actualValue,
            };
          }
          else if(description.idType == "tag") {
            var failureObj = {
              ruleName: ruleName,
              expected: description.name + '\n' + description.matcher,
              actual: actualValue,
            };
          }
          failureList.push(failureObj);
        }
      }
      if(failureList.length > 0) {
        item.runs[runIndex].failures = failureList;
      }
    }
  }
  return report;
}

快速路线:

const router = express.Router();

router.post('/', authenticate, async (req, res) => {
  const runResponse = {
    webAudits: [],
    webJourneys: [],
    appJourneys: []
  };
  console.log('router');

  const webAudits = await webAuditsFailures(req);
  runResponse.webAudits = webAudits;

  res.status(201).json({ reports: runResponse });
  console.log('Success');
})

我的代码按顺序运行,但问题是即使函数执行没有完成,函数webAuditsFailures也会被重新调用。这将打印到控制台:
here check wa here check wa success

我无法理解正在发生的事情以及我做错了什么......自从我面对这个问题并且我尝试的一切都无法正常工作后的两周内......
如果有其他方法可以在不使用async/await的情况下实现此目的,那么我可以使用它们。

以下是waComplianceBusinesswaRuleOverviewwaConditionOverview函数:

import deferred from 'deferred';

export function waComplianceBusiness(req, runId, callback) {
  var def = deferred();

  const apiToken = req.currentUser.apiToken;
  const payload = {
    'Authorization': 'api_key ' + apiToken
  }

  const options = {
    'method': 'get',
    'gzip': true,
    'headers': payload,
    'content-type': 'application/json',
    'json': true,
    'url': 'api-url'
  }

  request(options, (error, response, body) => {
    def.resolve(body);
  });

  return def.promise;
}

export function waRuleOverview(req, runId, ruleId) {
  var def = deferred();
  const apiToken = req.currentUser.apiToken;
  const payload = {
    'Authorization': 'api_key ' + apiToken
  }

  const options = {
    'method': 'get',
    'gzip': true,
    'headers': payload,
    'content-type': 'application/json',
    'json': true,
    'url': 'api-url'
  }

  request(options, (error, response, body) => {
    def.resolve(body);
  });

  return def.promise;
}

export function waConditionOverview(req, body) {
  var def = deferred();

  const apiToken = req.currentUser.apiToken;
  const payload = {
    'Authorization': 'api_key ' + apiToken
  }

  const options = {
    'method': 'post',
    'gzip': true,
    'headers': payload,
    'body': body.payload,
    'content-type': 'application/json',
    'json': true,
    'url': 'api-url'
  }

  request(options, (error, response, body) => {
    def.resolve(body);
  });

  return def.promise;
}

0 个答案:

没有答案