【问题标题】:how to stop infinite loop when using callback inside while-loop in js在js中的while循环中使用回调时如何停止无限循环
【发布时间】:2022-11-26 21:29:18
【问题描述】:

所以我正在创建一个像 Connect 4 这样的游戏,它要求用户输入但我面临的问题是我在 while 循环中使用了回调(readline.question)函数,每当我启动代码时它就开始无限循环而不询问一个用户的问题。我怎样才能暂停一段时间直到用户回答?我必须在不使用的情况下解决这个问题异步/等待.

 function fetchColumn(player, callback) {
   io.question(`Player ${player}, which Column? `, line => {
        console.log(`You requested "${line}"`);
        chosen_column = line;
        callback(); 
    });
}
let connect4 = new Connect4();
connect4.makeBoard(numRows, numCols, winLength);
while (game_over == 0) {
    connect4.printBoard();
    fetchColumn(current_player,()=>{
    
        console.log(`you entered ${chosen_column}`);
        
        if (chosen_column != 'Q' && chosen_column != 'q') {
            move_status = connect4.place_piece(chosen_column, current_player);
            x_in_a_row_status = connect4.x_in_a_row(current_player);
            
            if (move_status == 0) {
// Further code-------

这就是我在终端中得到的。

Player 1, which Column? 
A B C D E F G 
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . . 
Player 1, which Column? 
A B C D E F G
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .

----------Keep repeating----------

【问题讨论】:

  • 什么是io.question
  • 它的 readline.question 用于从用户那里获取输入。

标签: javascript node.js callback infinite-loop readline


【解决方案1】:

如果要在循环中调用异步函数,可以将whileawait 结合使用:

function fetchColumnAsync(player) {
  return new Promise(function(resolve, reject) {
    io.question(`Player ${player}, which Column? `, line => {
      console.log(`You requested "${line}"`);
      chosen_column = line;
      resolve(); 
    });
  });
}
let connect4 = new Connect4();
connect4.makeBoard(numRows, numCols, winLength);
while (game_over == 0) {
  connect4.printBoard();
  await fetchColumnAsync(current_player);
  console.log(`you entered ${chosen_column}`);
  ...
}

或递归结合回调函数:

function loop() {
  if (game_over == 0) {
    connect4.printBoard();
    fetchColumn(current_player, () => {
      console.log(`you entered ${chosen_column}`);
      ...
      loop();
    });
  }
}
let connect4 = new Connect4();
connect4.makeBoard(numRows, numCols, winLength);
loop();

但是您不能将 while 与回调结合使用,因为 while 循环的第二次迭代开始同步地, 在调用回调函数之前异步地.换句话说,它给出了一个无限循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-29
    • 2012-10-18
    • 1970-01-01
    • 2014-03-29
    • 2012-12-24
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    相关资源
    最近更新 更多