Home > Back-end >  node.js readline with if / else statements - gets stuck if empty input
node.js readline with if / else statements - gets stuck if empty input

Time:12-21

I want to output questions and receive answers as input in a terminal. For each question, there is a check, in this case if the input was provided or not. If it is, next question should be outputted; if not, question should be looped.

If input is provided every time, resolve() gets called and moves on to the next question, as it should. But the problem happens if the first time an empty input is sent. It kinda gets stuck and the resolve() does not work any more

const rdline = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let userName, userSurname = "";

1st question

const question_name = () => {
    return new Promise((resolve) => {
        rdline.question("What's your name?\n", name => {
            if (name) {
                userName = name;
                resolve();
            } else {
                question_name();

            }
        });
    });

};

2nd question

const question_surname = () => {
    return new Promise((resolve) => {
        rdline.question("What's your surname?\n", surname => {
            if (surname) {
                userSurname = surname;
                resolve();
            } else {
                question_surname();
            }
        });
    });
};

call both questions

const askUser = async () => {
    await question_name();
    await question_surname();
    console.log(`Hi, ${userName} ${userSurname}`);
    rdline.close();
};

askUser();

CodePudding user response:

It seems you're not resolving the data and are expecting userName and userSurname to exist in askUser.

Instead resolve the answers, and the repeat questions, and assign them inside askUser:

// mock rdline
const rdline = {
  question: (a,b) => a.match(/surname/) ? b('Test') : b('User'),
  close: () => {}
};

const question_name = () => {
    return new Promise((resolve) => {
        rdline.question("What's your name?\n", name => {
            if (name) {
                resolve(name);
            } else {
                resolve(question_name());
            }
        });
    });

};

const question_surname = () => {
    return new Promise((resolve) => {
        rdline.question("What's your surname?\n", surname => {
            if (surname) {
                resolve(surname);
            } else {
                resolve(question_surname());
            }
        });
    });
};

const askUser = async () => {
    const userSurname = await question_name();
    const userName = await question_surname();
    console.log(`Hi, ${userName} ${userSurname}`);
    rdline.close();
};

askUser();

CodePudding user response:

There is a function called resolve in js. I suggest you do function questionname() {...} instead of calling an arrow function. Also, use another name instead of resolve.

  • Related