node.jsasync-awaitread-eval-print-loopnode-repl

Using Node.js's REPL eval with an async function


I am using the Node.js REPL module to implement a REPL.

Here's how I start the REPL:

const cli = repl.start({ eval: evals });

I have a function, answer, that takes a few arguments and returns the answer. answer is async. evals is a function that bridges what REPL needs for the eval function with what my answer function provides. evals looks at follows.

const evals = (command, context, file, callback) => {
  (async () =>
    callback(null, await answer(command, arg1))
  )()
};

Now, the good thing is, it works. But this looks far more complicated than it needs to be. Am I missing some way to make this considerably simpler to maintain?

(Here is the code in context)


Solution

  • I think making the evals function directly async should work:

    const evals = async (command, context, file, callback) => {
        callback(null, await answer(command, arg1));
    };
    

    Or you could avoid async/await and use Promise.then directly; that might be clearer in this case:

    const evals = (command, context, file, callback) => {
        answer(command, arg1)
            .then((result) => callback(null, result));
    };
    

    (In either case you could probably omit the braces, though I’m not sure if I like that better or not.)