How to call async method from node console?

Dmitriano

I have a Bot class with async printInfo method:

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

If I start 'node', create the object from the console and call the method:

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

there is an annoying extra information appears in the console:

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

is there a way to suppress it?

'await' keyword produces an error here.

theonlygusti

That "annoying" extra info is the Promise object that TradeBot#printInfo returns.

The node REPL by default prints the returned value of anything you call:

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

That is why you get the extra output.

Knowing this, we can see the question has been asked and answered before: Prevent Node.js repl from printing output

Simply, you can suppress the extra output by writing this line at the REPL instead:

bot.printInfo(), undefined;

If you want you can start node with an extra argument, defining the REPL to use, as 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);
        }
    });
'

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related