[英]Using ES6 generators from the answer block of a nodejs readline
我試圖將注意力集中在生成器的概念上,並為此構建示例命令行“ game”。 但是,在第二個問題中,我輸入的輸入顯示為三倍,即一次輸入“ e”時顯示為“ eee”。 我究竟做錯了什么?
似乎每個questionToAnswer函數實例都會創建一個新的readline接口,並且沒有正確關閉它,這將解釋輸入的三倍。 但是, rl.close;
應該關閉界面AFAIK。
const readline = require('readline');
const environments = ['forest', 'lava cave', 'island hut', 'mountainside shack', 'valley'];
const questionToAnswer = (q, a = null) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(q, (answer) => {
if (a !== null) console.log(a, answer);
rl.close;
theStory.next();
});
}
function* eventsOfStory(e) {
console.log('Welcome to the Great Adventure!');
yield questionToAnswer('What shall ye name your hero? ', 'Alright! Your hero\'s name shall be');
yield questionToAnswer(`You wake up in a ${environments[Math.floor(Math.random() * environments.length)]}.`);
yield questionToAnswer('How will you survive?', 'Sounds like a plan!');
yield endOfStory();
}
const endOfStory = () => {
console.log('End of story.');
process.exit();
}
// iterator
let theStory = eventsOfStory();
theStory.next();
期望的結果是,在回答當前問題或在顯示事實並且沒有預期答案時,在回答當前問題或按Enter鍵之后觸發任何后續事件。
您的rl.close;
應該是rl.close();
。
( rl.close
是一個函數,因此您需要調用它以關閉接口)
例如:
const readline = require('readline');
const environments = ['forest', 'lava cave', 'island hut', 'mountainside shack', 'valley'];
const questionToAnswer = (q, a = null) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(q, (answer) => {
if (a !== null) console.log(a, answer);
rl.close();
theStory.next();
});
}
function* eventsOfStory(e) {
console.log('Welcome to the Great Adventure!');
yield questionToAnswer('What shall ye name your hero? ', 'Alright! Your hero\'s name shall be');
yield questionToAnswer(`You wake up in a ${environments[Math.floor(Math.random() * environments.length)]}.`);
yield questionToAnswer('How will you survive?', 'Sounds like a plan!');
yield endOfStory();
}
const endOfStory = () => {
console.log('End of story.');
process.exit();
}
// iterator
let theStory = eventsOfStory();
theStory.next();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.