所以,我在过去的几天里一直试图解决这个问题,但是我在rl.question函数之后调用的方法会在它们应该被调用之前被调用。我试过直接调用这些函数并尝试返回结果,希望发生不同的事情,但同样的事情不断发生。
这是我的代码:
const Entity = require('./spireb/entities/Entity.js');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var askQuestion = function(question) {
return new Promise(resolve => {
rl.question(question, answer => {
return resolve([question, answer]);
});
});
};
var confirmAnswer = function([question, answer]) {
return new Promise(resolve => {
console.log(`You said: ${answer}`);
rl.question('Are you sure? (Y/N): ', answer0 => {
if(answer0.toUpperCase() == 'Y') {
return resolve(answer);
} else if(answer0.toUpperCase() == 'N') {
console.log('Ah, I must\'ve misheard!');
return askQuestion(question);
} else {
console.log('Sorry, could you repeat that?');
return confirmAnswer([question, answer]);
}
});
});
};
//Getting player username
(async () => {
let x = await askQuestion('What is your username?: ').then(confirmAnswer);
x.then(theirA => {
global.username = theirA;
rl.close();
});
})();
console.log(`Your username is ${global.username}`);
console.log('Ended.');
此代码通常会导致:
What if your username?: Your username is undefined
Ended
我理解为什么它告诉我我的用户名是未定义的,但为什么它会不断跳过它询问用户用户名?