gpt4 book ai didi

javascript - 异步 Node.JS 中的用户输入

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:15 25 4
gpt4 key购买 nike

在下面的代码中,我想要获取一个Grid,要求xy。然后我将再次获取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*

关于javascript - 异步 Node.JS 中的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30144374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com