My approach to this would be to use async generators.
Assuming you have an array of questions:
const questions = [
"How are you today ?",
"What are you working on ?",
"What do you think of async generators ?",
]
In order to use the await
keyword, you must wrap your program into an async IIFE.
(async () => {
questions[Symbol.asyncIterator] = async function * () {
const stdin = process.openStdin()
for (const q of this) {
// The promise won't be solved until you type something
const res = await new Promise((resolve, reject) => {
console.log(q)
stdin.addListener('data', data => {
resolve(data.toString())
reject('err')
});
})
yield [q, res];
}
};
for await (const res of questions) {
console.log(res)
}
process.exit(0)
})();
Expected results:
How are you today ?
good
[ 'How are you today ?', 'good\n' ]
What are you working on ?
:)
[ 'What are you working on ?', ':)\n' ]
What do you think about async generators ?
awesome
[ 'What do you think about async generators ?', 'awesome\n' ]
If you want to get questions an answers altogether, you can achieve this with a simple modification:
const questionsAndAnswers = [];
for await (const res of questions) {
// console.log(res)
questionsAndAnswers.push(res)
}
console.log(questionsAndAnswers)
/*
[ [ 'How are you today ?', 'good\n' ],
[ 'What are you working on ?', ':)\n' ],
[ 'What do you think about async generators ?', 'awesome\n' ] ]
*/