2 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個贊
我在 array 中存儲了幾個問題var questions=[]。我正在使用forEach遍歷數(shù)組并為每個問題輸入輸入并將其顯示在終端本身上。但它只詢問第一個問題,顯示響應(yīng)并停留在那里。它不會轉(zhuǎn)移到下一個問題。我應(yīng)該使用rl.close(),但在哪里。這是我的代碼Quiz.js。
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var questions=[
"Hi, What is your name?",
"I need your contact number also",
"Thanks! What is your favourite color?"
];
questions.forEach(myFunction);
function myFunction(item, index) {
rl.question(item, (answer) => {
console.log(`You said: ${answer}`);
});
rl.close(); //THIS IS IMMEDIATELY CLOSING AFTER THE FIRST QUESTION
}
請糾正我。

TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個贊
問完所有問題后,您是否嘗試關(guān)閉它?
我的意思是:
function myFunction(item, index) {
rl.question(item, (answer) => {
console.log(`You said: ${answer}`);
});
if (index === questions.length - 1) {
rl.close();
}
}
=== === ===
如果它仍然無法正常工作,請嘗試以下操作:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
var questions = [
'Hi, What is your name?',
'I need your contact number also',
'Thanks! What is your favourite color?',
];
const ask = (question) => {
return new Promise(resolve => rl.question(question, resolve))
}
const askAll = async (questions) => {
const answers = []
for (let q of questions) {
answers.push(await ask(q))
console.log('You said:', answers[answers.length - 1]);
}
return answers
}
askAll(questions).then(rl.close)
我關(guān)閉了函數(shù)的rl外部askAll,因?yàn)槲艺J(rèn)為函數(shù)最好不要知道資源管理之類的東西。
添加回答
舉報