代码之家  ›  专栏  ›  技术社区  ›  Finduilas

如何停止代码直到函数返回?

  •  0
  • Finduilas  · 技术社区  · 2 年前

    我已经构建了一个菜单,显示控制台中的菜单:

    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是从另一个运行getUserInputConfiguration的控制器导入的函数。该函数使用inquirer询问一些问题(使用inquirer.prompt)。这很好。

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

    }

    但是如果我在doConfiguration()之后运行位置代码

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

    它立即运行。我尝试使用wait-doConfiguration();但这是不允许的,并引发错误:

    SyntaxError:await仅在异步函数和顶层中有效 模块主体

    如何停止代码直到doConfiguration返回? 我想不通。

    1 回复  |  直到 2 年前
        1
  •  2
  •   TiagoLr    2 年前

    尝试包装 menu.question 使用async回调,然后您可以 await doConfiguration()

    如:

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