异步用户输入 Node.JS

User input in asynchronous Node.JS

在下面的代码中,我要get一个Grid,要求xy。那我再get Grid

然而,由于 Node.JS 是异步的,第二个 get 在请求 x 之后、x 给出之前和 y 之前执行被问到。

我应该在执行其余代码之前检查前面的过程是否已完成。据我所知,这通常是通过回调来完成的。我现在的回调好像不够用,这种情况下怎么强制同步执行?

我试图保留它 MCVE,但我也不想遗漏任何重要内容。

"use strict";
function Grid(x, y) {
  var iRow, iColumn, rRow;
  this.cells = [];
  for(iRow = 0 ; iRow < x ; iRow++) {
    rRow = [];
    for(iColumn = 0 ; iColumn < y ; iColumn++) {
      rRow.push(" ");
    }
    this.cells.push(rRow);
  }
}

Grid.prototype.mark = function(x, y) {
  this.cells[x][y] = "M";
};

Grid.prototype.get = function() {
  console.log(this.cells);
  console.log('\n');
}


Grid.prototype.ask = function(question, format, callback) {
 var stdin = process.stdin, stdout = process.stdout;

 stdin.resume();
 stdout.write(question + ": ");

 stdin.once('data', function(data) {
   data = data.toString().trim();

   if (format.test(data)) {
     callback(data);
   } else {
     stdout.write("Invalid");
     ask(question, format, callback);
   }
 });
}

var target = new Grid(5,5);

target.get();

target.ask("X", /.+/, function(x){
  target.ask("Y", /.+/, function(y){
    target.mark(x,y);
    process.exit();
  });
});

target.get();

how do I force synchronous execution?

您不能强制同步执行。您可以通过在回调(异步回调)中的异步操作之后移动您希望执行的代码来使执行顺序(同时仍然是异步的)。

在你的情况下,你似乎在寻找

var target = new Grid(5,5);
target.get();
// executed before the questions are asked
target.ask("X", /.+/, function(x){
  // executed when the first question was answered
  target.ask("Y", /.+/, function(y){
    // executed when the second question was answered
    target.mark(x,y);
    target.get();
    process.exit();
  });
});
// executed after the first question was *asked*