2015-05-09 53 views
1

在下面的代码中,我想要get a Grid,请求xy。然后我再次getGrid用户输入异步Node.JS

然而,由于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(); 
+0

你不能强迫同步执行。尽管(尽管仍然是异步的),你可以顺序执行。只需在第二个'target.ask(...)'调用之前移动第二个'target.get()'调用 - 在第一个回调中。 – Bergi

+0

@Bergi现在第二个'target.get()'将在'x'被放入之后执行,但仍然在'y'被提问之前执行。它比它更好,但是在执行第二个'target.get()'之前需要'y'。 – Mast

+0

哦,对,我没有真正得到你想要的。看起来你想把它放在'target.mark(x,y)'之后。 – Bergi

回答

1

如何强制同步执行?

您无法强制同步执行。您可以通过在回调(异步调用回调)内的异步操作之后移动您期望执行的代码来依次执行顺序执行(但仍为异步)。

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

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*