I know this may come across as a 'Noob Question', and I apologize in advance for asking something so simple. But I haven't been able to find much on this topic when searching online.
I'm trying to write a command line app in Node.js, however I haven't been able to figure out how to handle user input synchronously. I tried using async/await, but those seemed to have no effect. Instead I moved to promises, however the following code errors out with: TypeError: promise.resolve is not a function.
Reading the MDN it shows the Promise API as being new Promise(resolutionFunc, rejectionFunc). With those functions being called on resolution and rejection respectively.
I'm not quite sure what I'm doing wrong, but from what I understand it should only be executing the .then() after the previous promise is resolved. However that is not the case here:
My Code:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
let numbs = [];
function getInput(i) {
let promise = new Promise((resolve) => {
numbs[i] = resolve;
}, (reject) => {
// do nothing, shouldn't happen
});
rl.question(`Input #${i+1}: `, (input) => {
promise.resolve(Number.parseInt(input));
});
return promise;
}
getInput(0)
.then(getInput(1))
.then(() => {
console.log(numbs)
/*
rest of the program using those 2 inputs
*/
})
.catch((err) => {
// do nothing, and exit
});
Output:
$ node .\file.js
Input #1: Input #1:
[path removed]/file.js:18
promise.resolve(Number.parseInt(input));
^
TypeError: promise.resolve is not a function
at [path removed]/file.js:18:17
at Interface._onLine (readline.js:335:5)
at Interface._normalWrite (readline.js:482:12)
at ReadStream.ondata (readline.js:194:10)
at ReadStream.emit (events.js:315:20)
at addChunk (_stream_readable.js:296:12)
at readableAddChunk (_stream_readable.js:272:9)
at ReadStream.Readable.push (_stream_readable.js:213:10)
at TTY.onStreamRead (internal/stream_base_commons.js:186:23)