Node.js For-Loop和Readline函数调用?

时间:2017-03-30 13:31:03

标签: javascript node.js asynchronous ecmascript-6

我正在尝试输入一系列测试分数并确定它们在JavaScript中的平均值,我想我会试用Node.js.函数readTestScores()利用readline的question()方法 - 来自Node.js的Readline模块,获取内部嵌套for循环的最终考试分数,并自己调用question()获得7测试成绩。见下文(是的,我知道,我的代码看起来很混乱):

function readTestScores() {
    var score = 0;

    rl.question('Enter exam score:', (examScore) => {
        console.log("Enter test scores: ");
        for (var i=0; i < 7; i++) {
            rl.question('', (score) => {
            test_avg += score;
            });
        }
        rl.close();
    });
    test_avg /= 7;
}

当我运行我的代码时,当执行到达for循环时,它会跳过所有的question()调用,直到最后,我只能在程序终止之前输入一个值。有没有办法可以纠正这个问题?

编辑:这是我用来创建readline界面的代码:

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

1 个答案:

答案 0 :(得分:0)

以下是使用Readline计算平均值的一些代码,基于微小的cli教程:

'use strict';

var aiScores = [];
var iAverage;

function add(a, b) {
    return a + b;
}

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

rl.setPrompt('Enter exam score > ');
rl.prompt();

rl.on('line', (line) => {
  console.log(line);
  if (Number.isInteger(parseFloat(line))) {
      aiScores.push(parseFloat(line));
      console.log(aiScores);
      console.log(parseFloat(line));
      iAverage = (aiScores.reduce(add, 0)/aiScores.length);
      console.log('Current average = ' + iAverage);
  } else {
      switch(line.trim()) {
        case 'hello':
          console.log('world!');
        case 'close':
          rl.close();
          break;
        default:
          console.log(`Say what? I might have heard '${line.trim()}'`);
          break;
      }
  }
  rl.prompt();
}).on('close', () => {
  console.log('Have a great day!');
  process.exit(0);
});