程序退出调用堆栈的时间比预期的早

时间:2018-11-27 23:25:42

标签: javascript node.js

我有一个程序似乎比预期的要早退出函数调用堆栈。 askPersonalInformation()调用askMealPlanInformation(),然后依次调用askMealInformation()。 askMealPlanInformation()打算执行n次,并且在每个调用中,askMealInformation()打算执行m次。但是对于第一个askMealPlanInformation()调用,askMealInformation()会按预期被调用m次,但是在首次执行后不再调用askMealPlanInformation()。

在对此进行故障排除时,我编写了一个有效的inner()/ outer()函数程序,但看不到为什么整个程序不起作用。

完整程序(无效):

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

var askPersonalInformation = function() {
  var age;
  var gender;
  var weight_lbs;
  var height_inches;
  var activityLevel;
  var numberOfMeals;

  rl.question('Age? ', (answer) => {
    age = answer;
    rl.question ('Gender (Male/Female)? ', (answer) => {
      gender = answer;
      rl.question('Weight (lbs): ', (answer) => {
        weight_lbs = answer;
        rl.question('Height (inches): ', (answer) => {
          height_inches = answer;
          rl.question('Number of meals? ', (answer) => {
            numberOfMeals = answer;
            askMealPlanInformation(0, numberOfMeals);
          })
        });
      });
    });
  });
}

var askMealPlanInformation = function(counter, limit) {
    rl.question("New Meal Name: ", (answer) => {
      rl.question("Meal Size: ", (answer) => {
        askMealInformation(0,3);
        if (counter < limit - 1) {
          askMealPlanInformation(counter + 1, limit);
        } else {
          console.log(counter);
          return;
        }
      })
    });
}

var askMealInformation = function (counter, limit) {
  var mealStatus = "Current Meal Status: {To be included}\r\n\r\n";
  var actionPrompt = "Add, Remove, or Edit Food Entry for Current Meal?\r\nKey\tAction\r\n1\tAdd\r\n2\tEdit\r\n\r\nChoice: ";
  console.log(mealStatus);
  rl.question(actionPrompt, (answer) => {
    rl.question("Select Food Group: ", (answer) => {
      rl.question("Select Food: ", (answer) => {
        rl.question("Select Servings: ", (answer) => {
          if (counter < limit - 1) {
            console.log(counter);
            askMealInformation(counter + 1, limit);
          } else {
            console.log(counter);
            return;
          }
        })
      })
    })
  });
}

askPersonalInformation();

示例程序(有效):

function outer(counter, limit) {
  console.log("Outer: " + counter);
  inner(0, 3);
  if (counter < limit - 1) {
    outer(counter + 1, limit);
  } else {
    return
  }
}

function inner(counter, limit) {
  if (counter < limit - 1) {
    console.log("\tInner: " + counter);
    inner(counter + 1, limit);
  } else {
    console.log("\tInner: " + counter);
    return;
  }
}

outer(0, 3);

0 个答案:

没有答案