For loop doesn’t continue after using readline question.

huangapple go评论95阅读模式
英文:

For loop doesn't continue after using readline question

问题

我想循环x次,每次都执行readline。在我的代码中,在读取第一个输入后,循环永远不会进入第二次迭代。我认为这与我创建的内联函数有关,但我卡在了为什么。有什么帮助吗?

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
rl.question("好的,将会有多少名玩家(最多8名玩家)\n", function(playerCount) {
  const parsedInput = parseInt(playerCount);
  if (parsedInput > 0 && parsedInput <= 8) {
    let listOfNames = [];
    for (let i = 0; i < parsedInput; i++) {
      rl.question(`输入第${i}名玩家的名字\n`, function gatherNames(name) {
        listOfNames.push(name);
        console.log(`已将${name}添加到玩家列表中\n`);
      });
    }
  }
});
英文:

I want to loop x amount of times while doing a readline each time. In my code after reading in the first input, the loop never moves onto the second iteration. I assume it has something to do with the inline function I created but I'm stuck as to why. Any help?

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
rl.question(&quot;Ok how many players will there be (MAX: 8 players)\n&quot;, function(playerCount) {
  const parsedInput = parseInt(playerCount);
  if (parsedInput &gt; 0 &amp;&amp; parsedInput &lt;= 8) {
    let listOfNames = [];
    for (let i = 0; i &lt; parsedInput; i++) {
      rl.question(`Enter name #${i}\n`, function gatherNames(name) {
        listOfNames.push(name);
        console.log(`Added ${name} to list of players\n`);
      });
    }
  }
});

答案1

得分: 2

You are calling rl.question(...) parsedInput times before you even enter the response from the first one. The library doesn't seem to support that and just silently fails.

You need to call the next rl.question(...) only after you receive a response from the current question. For that, you will need to call it inside the callback and can't use the for loop. You will need to rely on the size of the listOfNames array to know when to stop.

A better approach would be with async/await code, i.e., promises. It would make extending the functionality a lot simpler and more straightforward. The flow of the code is a lot closer to what you have tried.

英文:

You are calling rl.question(...) parsedInput times, before you even enter the response from the first one. The library doesn't seem to support that and just silently fails.

You need to call the next rl.question(...) only after you received response from the current question.
For that you will need to call in inside the callback and can't use the for loop. You will need to rely on the size of the listOfNames array to know when to stop.

readline = require(&quot;readline&quot;);

const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
});
rl.question(&quot;Ok how many players will there be (MAX: 8 players)\n&quot;, function(playerCount) {
	const parsedInput = parseInt(playerCount);
	if (parsedInput &gt; 0 &amp;&amp; parsedInput &lt;= 8) {
		let listOfNames = [];
		const add_name = function(name) {
			listOfNames.push(name);
			console.log(`Added ${name} to list of players\n`);
            // if the array doesn&#39;t have the desired number of names, ask again.
			if (listOfNames.length &lt; parsedInput) {
				rl.question(`Enter name #${listOfNames.length}\n`, add_name);
			}
            // else print them out and end it
			else {
				console.log(listOfNames)
				rl.close();
			}
		}
		rl.question(`Enter name #0\n`, add_name);
	}
});

A better approach would be with async/await code i.e. promises.
It would make extending the functionally a lot simpler and straight forward.
The flow of the code is a lot closer to what you have tried.

const readlinePromises = require(&#39;readline/promises&#39;);

const rl = readlinePromises.createInterface({
	input: process.stdin,
	output: process.stdout,
});
(async () =&gt; {
	const playerCount = await rl.question(&quot;Ok how many players will there be (MAX: 8 players)\n&quot;);
	const parsedInput = parseInt(playerCount);
	if (parsedInput &gt; 0 &amp;&amp; parsedInput &lt;= 8) {
		let listOfNames = [];
		for (let i=0; i&lt;parsedInput; i++) {
			const name = await rl.question(`Enter name #${i}\n`);
			listOfNames.push(name);
			console.log(`Added ${name} to list of players\n`);
		}
		console.log(listOfNames);
	}
	rl.close();
})();

huangapple
  • 本文由 发表于 2023年1月4日 06:50:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/74999414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定