[英]User input in asynchronous Node.JS
在下面的代碼,我想get
一個Grid
,要求x
和y
。 然后,我將再次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();
如何強制同步執行?
您不能強制同步執行。 但是,您可以通過在回調(異步調用)內部執行異步動作之后移動希望執行的代碼,從而使執行順序化(盡管仍然是異步的)。
就您而言,您似乎正在尋找
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*
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.