在收到用户输入之前,如何阻止? [英] How can I block until user-input received?

查看:82
本文介绍了在收到用户输入之前,如何阻止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现以下脚本:

I am trying to implement the following script:

一个函数试图执行一个异步调用,如果抛出异常,则提示用户输入该函数是否应该再次运行.

A function tries to execute an asynchronous call, and if an exception is thrown then the user is prompt to input whether or not the function should run again.

如果用户输入"y",则应重复该过程.

If the user inputs "y", then the procedure should repeat.

如果用户输入"n",则该过程应终止.

If the user inputs "n", then the procedure should terminate.

如果都不是,则该问题应重复.

If neither, then the question should repeat.

在用户输入"y"或"n"之前,整个脚本的执行都应阻塞.

The execution of my entire script should block until either "y" or "n" are input by the user.

这是我到目前为止所拥有的(借助于此答案):

Here is what I have so far (with the help of this answer):

async function sendSignedTransaction(rawTransaction) {
    try {
        return await web3.eth.sendSignedTransaction(rawTransaction);
    }
    catch (error) {
        process.stdout.write(error.message + "; try again (y/n)?");
        process.stdin.on("data", async function(data) {
            switch (data.toString().trim()) {
                case "y": return await sendSignedTransaction(rawTransaction);
                case "n": process.exit();
                default : process.stdout.write("try again (y/n)?");
            }
        });            
    }
}

问题在于脚本的执行一直持续到用户输入"y"或"n"为止.

The problem is that the execution of the script continues without waiting until the user has inputted either "y" or "n".

推荐答案

这是因为process.stdin操作也是 异步的,因此无论调用初始sendSignedTransaction的位置如何,如果抛出错误,都会(当前)该代码块中没有阻止该函数退出的内容.

That's because process.stdin operations are also asynchronous so wherever you invoke the initial sendSignedTransaction, if it throws an error there is nothing (currently) in that block of code that stops the function from exiting.

您混合了Promise&经典的回调代码.如果您要确保调用者等到功能完全完成后再进行操作,则可以将完整功能转换为Promise,这样您就可以更好地控制它了.

You have a mixture of Promise & classic callback code. If you want to make sure the caller waits until the function has completely finished, then you can convert the full function into a Promise which gives you more control over it e.g.

function sendSignedTransaction(rawTransaction) {
  return new Promise(async (resolve, reject) => {
    try {
      const result = await web3.eth.sendSignedTransaction(rawTransaction);
      return resolve(result);
    } catch (e) {
      process.stdout.write(e.message + "; try again (y/n)?");
      process.stdin.on('data', async data => {
        switch (data.toString().trim()) {
          case "y": return resolve(await sendSignedTransaction(rawTransaction));
          case "n": return process.exit();
          default : return process.stdout.write("try again (y/n)?");
        }
      });
    }
  });
}

这篇关于在收到用户输入之前,如何阻止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆