Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading