-1

我正在运行以下代码以从 nodejs 中的终端获取输入(我选择了这种方法,因为它不需要依赖项)并且我需要它同步工作。它位于一个被for循环重复调用的函数内部,因此在其当前的异步状态下,它会导致一些问题。

这是我想要同步的功能:

standard_input.on('data', function (data) {
 choice = data;
 if (choice == 1) response = rp.r1;
if (choice == 2) response = rp.r2;


console.log("[" + character.name + "]: " + response);
});

谢谢你的帮助!

编辑:我的情况和代码的更详细解释如下:

我有一个for调用同步函数的循环,conversation(). 在这个函数中有一段代码要求for循环停止,直到用户输入一些内容。我正在寻求一种方法来做到这一点,或者使用我现有的获取用户输入的方法(如上所示)或不同的方法。

编辑 2:续集:

更完整的代码片段可帮助您解答问题,因为提供的某些答案对我不起作用,因为我对自己要做什么还不够清楚。

function conversation(character, num, rp) {
if (negStreak >= 4) {
  return false;
}
var choice;
var response;

console.log("CHOICES:");
console.log("(1): " + rp.c1);
console.log("(2): " + rp.c2);
console.log("Type 1 or 2 and hit Enter.");

standard_input.on('data', function (data) { //this is how i'm getting input
 choice = data;
 if (choice == 1) response = rp.r1;
if (choice == 2) response = rp.r2;
negStreak++

console.log("[" + character.name + "]: " + response);
});

}

function game(char) {
  negStreak = 0;
if (char.name == "Vern") array = vern_conv;
if (char.name == "Jericho") array = jericho_conv;
if (char.name == "Las") array = las_conv;
if (char.name == "char3") array = char3_conv;
if (char.name == "char4") array = char4_conv;

for (i = 0; i < array.length; i++) { //this is the for loop i'm talking about
var reactionPair = array[i];
conversation(char, i, reactionPair);
}
}
4

2 回答 2

0

如果正确理解了您的需求,您将需要使用 async 并 await 等待在您的函数中分配数据,因此您可能想尝试这样的事情

    async function userinput(){
   return await new Promise(resolve=>{
    standard_input.on('data', function passdata (data) {
      standard_input.removeEventListener("data",passdata);

      choice = data;
      if (choice == 1) resolve(response = rp.r1);
     if (choice == 2) resolve(response = rp.r2)
     console.log("[" + character.name + "]: " + response);
     });
  })
}
userinput()
于 2020-06-16T00:26:48.690 回答
0

而不是将您的输入包装在 for 循环中......

for (loop var) {
  input = prompt_for_input <--- oh no, this is inherently async
  do something with input
}

让你的循环作为输入的结果进行迭代,所以它看起来像这样......

prompt_for_input
whenWeGetInput(
  do something with input
  prompt_for_input // <-- this is your loop now
) 

nodejs readline允许使用 createInterface 进行这种循环...

const readline = require('readline')
let rl = readline.createInterface(process.stdin, process.stdout)

rl.setPrompt('$ ')
rl.prompt()

rl.on('line', choice => {
  switch(choice.trim()) {
    case '1':
      console.log('you typed 1')
      break
    case '2':
      // and so on
    default:
      console.log(`you typed something else: ${choice}`)
      break
    }
    rl.prompt() // <-- this is your loop now
}).on('close', () => {
  process.exit(0)
})
于 2020-06-16T00:46:55.790 回答