I am trying to write a simple app where I ask a sequence of simple arithmetic questions and at the end tell the % correct. I started with this:
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
var correct = 0;
for (i = 0; i < 10; i++) {
var num1 = between(0,9);
var num2 = between(0,9);
readline.question(num1 + " + " + num2 + " = ", answer => {
if ((num1 + num2) == answer) {
correct++;
}
});
}
console.log("percentage: " + correct/10);
function between(min, max) {
return Math.floor(
Math.random() * (max - min) + min
)
}
Then realized that I need to use Await and Promise so I switched to this:
function askQuestion(query) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise(resolve => rl.question(query, ans => {
rl.close();
resolve(ans);
}))
}
function between(min, max) {
return Math.floor(
Math.random() * (max - min) + min
)
}
var correct = 0;
for (i = 0; i < 10; i++) {
var num1 = between(0,9);
var num2 = between(0,9);
const ans = await askQuestion(num1 + " + " + num2 + " = ");
if (ans == (num1 + num2)) {
correct++;
}
}
console.log("percentage: " + (correct/10))
But I get the error
const ans = await askQuestion(num1 + " + " + num2 + " = ");
^^^^^
SyntaxError: await is only valid in async function
What am I doing wrong?