代码块工作,返回没有

时间:2017-04-28 20:38:04

标签: node.js promise

甚至不确定如何准确地说出来。

我有两个功能,你可以在下面看到。 checkDescription按预期工作并返回,然后拒绝承诺。第二块" checkAwsVsSgs"也按预期执行,但从不拒绝承诺甚至执行test console.log部分。

// Library Module, Public functions
module.exports = {


  checkSG: function(block) { 
    return new Promise((resolve, reject) => {
      let found = false;

      Object.keys(awsSecurityGroups).forEach( (key)=> {
        let group = awsSecurityGroups[key];
        if (block.local_action.name === group.GroupName) {
          found = true;

          if (!checkDescription(group, block)) { reject("Description doesn't match.") }
          if (!checkAwsVsSgs(group, block)) { console.log("!!!!! I'm never called"); reject("Found rules in aws that are not in sgs") }

        }
      });

      resolve(found);
    });
  },

};

// Private functions
function checkDescription(group, block) {
  return group.Description === block.local_action.description
}

function checkAwsVsSgs(group, block) { // Look for rules that are in AWS but not sgs
  group.IpPermissions.forEach( (awsRule) => {
    let foundRuleMatch = false;
    block.local_action.rules.forEach ( (blockRule) => {
      //console.log("Checking FromPort %s vs %s and ToPort %s vs %s for %s", awsRule.FromPort, blockRule.from_port, awsRule.ToPort, blockRule.to_port, group.GroupName)
      if (awsRule.ToPort === blockRule.to_port && awsRule.FromPort === blockRule.from_port) { foundRuleMatch = true }
    });
    if (!foundRuleMatch) {
      console.log("Error: Could not find matching rule for %s FromPort: %s ToPort: %s", group.GroupName, awsRule.FromPort, awsRule.ToPort);
      return false;
    }
  });
  return true;
}

1 个答案:

答案 0 :(得分:0)

这是因为您总是在true中返回checkAwsVsSgsreturn false;中的forEach用于forEach函数,而不用于外部函数。你需要做这样的事情:

function checkAwsVsSgs(group, block) { // Look for rules that are in AWS but not sgs
  var found = true;
  group.IpPermissions.forEach( (awsRule) => {
    let foundRuleMatch = false;
    block.local_action.rules.forEach ( (blockRule) => {
      //console.log("Checking FromPort %s vs %s and ToPort %s vs %s for %s", awsRule.FromPort, blockRule.from_port, awsRule.ToPort, blockRule.to_port, group.GroupName)
      if (awsRule.ToPort === blockRule.to_port && awsRule.FromPort === blockRule.from_port) { foundRuleMatch = true }
    });
    if (!foundRuleMatch) {
      console.log("Error: Could not find matching rule for %s FromPort: %s ToPort: %s", group.GroupName, awsRule.FromPort, awsRule.ToPort);
      found = false;
      return;
    }
  });
  return found;
}

此外,如果您想测试数组中的某些元素是否通过某些条件,请考虑对所有元素使用Array.prototype.some()Array.prototype.every()