Search code examples
node.js

How do I halt my code untill there is a return from a function?


I have build a menu that shows a menu in the console:

async function showMain() {
    process.stdout.write('\033c');

    // Log the menu
    console.log(
        'Main menu\n\n' +
        '1 = A configuration\n' +
        '2 = B configuration\n' +
        '4 = Exit'
        );

    // Check if there is already a menu active. If true, close it.
    if(menu) menu.close();

    //Creates a readline Interface instance
    menu = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    // Ask question
    menu.question('Where to go? ', function(input) {
        switch(input) {
            case '1': const something = doConfiguration();
showMain(); break;
            case '2': process.exit(); break;
            default: showMain() /* show menu again if input does not match */;
        }
    });
}

doConfiguration is a function that is imported from another controller that runs getUserInputConfiguration. That function uses inquirer to ask some questions (with inquirer.prompt). That works fine.

async function doConfiguration() {

try {
    const answers = await getUserInputConfiguration(chalk,inquirer);
    // do something
    return true;
} catch (error) {
      console.log('Error:', error);
}
return false;

}

But if I run place code after doConfiguration()

case '1': const something = doConfiguration();
showMain();

It runs it immediatly. I tried to use await doConfiguration(); but it isn't allowed and throws an error:

SyntaxError: await is only valid in async functions and the top level bodies of modules

How can I halt the code untill there is a return from doConfiguration ? I couldn't figure it out.


Solution

  • Try wrapping menu.question callback with async, then you can await doConfiguration()

    eg:

    menu.question('Where to go? ', async function(input) {
      ...
      const something = await doConfiguration();
    }