用户inputasynchronousNode.JS
在下面的代码中,我想要一个Grid
,请求x
和y
。 然后我会再次get
Grid
。
但是,由于Node.JS是asynchronous的,所以在请求x
之前,在给定x
之前和询问y
之前执行第二个get
。
在执行其余的代码之前,我应该检查先前的过程是否已经完成。 就我所知,这通常是通过callback完成的。 我目前的callback似乎不够,在这种情况下,我如何强制同步执行?
我试图保持它的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();
我如何强制同步执行?
你不能强制同步执行。 您可以通过在callback(asynchronous调用callback)内的asynchronous操作之后移动您期望执行的代码来依次执行(仍然是asynchronous的)执行。
就你而言,你似乎在寻找
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*