【问题标题】:How to call async method from node console? [duplicate]如何从节点控制台调用异步方法? [复制]
【发布时间】:2018-12-16 23:41:54
【问题描述】:

我有一个带有异步 printInfo 方法的 Bot 类:

class TradeBot {
    async printInfo() { //..... }
}

如果我启动“节点”,从控制台创建对象并调用方法:

>const createBot = require ('./BotFactory');
>const bot = createBot();
>bot.printInfo();

控制台中出现了令人讨厌的额外信息:

Promise {
  <pending>,
  domain:
 Domain {
 domain: null,
 _events: { error: [Function: debugDomainError] },
 _eventsCount: 1,
 _maxListeners: undefined,
 members: [] } }

有没有办法抑制它?

'await' 关键字在这里产生错误。

【问题讨论】:

  • “烦人的额外信息”正是printInfo 返回的……一个承诺。您不能在异步函数之外等待(还)。您可以使用异步 IIFE 或使用承诺链。
  • bot.printInfo.then(infoProbably =&gt; console.log(infoProbably))
  • 这是因为你在使用 promises 如果你的代码是同步的,你可以省略 async 字,如果不是,你应该了解更多关于如何处理 promises developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • Phil,据我所知,这也返回了 Promise
  • @Phil ,据我所知,这也返回 Promise

标签: javascript node.js


【解决方案1】:

那个“烦人”的额外信息是 TradeBot#printInfo 返回的 Promise 对象。

默认情况下,节点 REPL 会打印您调用的任何内容的返回值:

> console.log('Hi')
Hi
undefined
> 2
2
> function hello() {
... return 5;
... }
undefined
> hello()
5

这就是你得到额外输出的原因。

知道了这一点,我们可以看到问题已经被问过和回答过:Prevent Node.js repl from printing output

简单地说,你可以通过在 REPL 中写入这一行来抑制额外的输出:

bot.printInfo(), undefined;

如果您愿意,可以使用额外的参数 defining the REPL to use 启动节点,如 this answer recommends

node -e '
    const vm = require("vm");
    require("repl").start({
        ignoreUndefined: true,
        eval: function(cmd, ctx, fn, cb) {
            let err = null;
            try {
                vm.runInContext(cmd, ctx, fn);
            } catch (e) {
                err = e;
            }
            cb(err);
        }
    });
'

【讨论】:

  • 也可以使用void bot.printInfo()
猜你喜欢
  • 2016-07-20
  • 2017-05-19
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多