2015-05-09 55 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*