[英]NodeJS - readline calback loops itself
運行問題后應該執行 readline 回調,對嗎? 但是如果我傳遞一個字符串使其看起來像一個輸入,那么第二個問題根本不會執行。
rl.question(questions[answers.length], questionAnswered; // Works fine. Asks all question.
node .\questions.js
What is your name? test
1
Where do you live? test
2
What are you going to do with nodejs? test3
3
Thanks for the answers!!
[ 'test', 'test', 'test3' ]
通過“測試”作為輸入不能按預期工作。 我期待它仍然會問這個問題。
rl.question(questions[answers.length], questionAnswered('test')); // Will not ask second and third question.
node .\questions.js
What is your name? test
1
2
3
Thanks for the answers!!
[ 'test', 'test', 'test' ]
這是完整的代碼:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const questions = [
"What is your name? ",
"Where do you live? ",
"What are you going to do with nodejs? "
];
const createQuestions = (questions, done) => {
const answers = [];
const [firstQuestion] = questions;
questionAnswered = (answer) => {
answers.push(answer);
console.log(answers.length);
if (answers.length < questions.length) {
console.lol(answers.length);
rl.question(questions[answers.length], questionAnswered; // Works fine. Asks all question.
rl.question(questions[answers.length], questionAnswered('test')); // Will not ask second question.
} else {
done(answers);
}
};
rl.question(firstQuestion, questionAnswered);
};
createQuestions(questions, answers => {
console.log("Thanks for the answers!!");
console.log(answers);
process.exit();
});
我認為您應該為您的問題使用工廠模式questionAnswered
function。
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const questions = [
"What is your name? ",
"Where do you live? ",
"What are you going to do with nodejs? "
];
const createQuestions = (questions, done) => {
const answers = [];
const [firstQuestion] = questions;
questionAnswered = (defaultAnswer) => {
return function (answer) {
if (defaultAnswer) {
answers.push(defaultAnswer);
}
else {
answers.push(answer);
}
if (answers.length < questions.length) {
rl.question(questions[answers.length], questionAnswered('test'));
}
else {
done(answers);
}
};
};
rl.question(firstQuestion, questionAnswered());
};
createQuestions(questions, answers => {
console.log('---->', answers);
rl.close();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.