In the following code, I want to get a Grid, ask for x and y. Then I'll get the Grid again.
However, due to Node.JS being asynchronous, the second get gets executed after asking for x, before x is given and before y is asked.
I should probably check if the earlier process has finished before executing the rest of the code. This is usually done by a callback, as far as I know. My current callback seems insufficient, how do I force synchronous execution in this case?
I've tried to keep it MCVE, but I didn't want to leave anything essential out either.
"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();
target.get()call right before your secondtarget.ask(…)call - inside the first callback.target.get()will be executed afterxis being put in but still beforeyis asked. It's better than it was, butyis required before the secondtarget.get()is executed.target.mark(x, y)call then.