Calling async function in a custom node

I know the async topic has been discussed in a few posts here.
But I have yet to find a step-by-step tutorial on how to call async function in a custom node.

I've tried the following

  • adding async keyword to my node function like this
module.exports = function(RED) {
    async function myNodeFunc(config) {
        let result = await myHelperFunction(msg, config);

With or without the async keyword above, however, this gives me the error below

SyntaxError: await is only valid in async function

How to achieve what I intend to do, i.e., calling an async function in the node input handler?

Sorry for the noob question, but I can't seem to find a straightforward instruction in the doc.

I think that the problem is with the way you are exporting - though I'm not sure as I've not done it the way you have. The only modules I have with async functions in them were either exported as closures or as a singleton class

Hi @kakyoism

If you want to use await inside the input handler, then you need to make sure you declare the input handler as an async function.

In the code you've shared, you've made the top level node constructor function async - which is not the same thing as making the input handler async.

module.exports = function(RED) {
   function myNodeFunc(config) {
        // Make the handler for the input event async
        this.on("input", async function(msg,send,done) {
            let result = await myHelperFunction(msg, config);

Thank you! @knolleary

@knolleary BTW, is there a way to turn on line numbers in the console error log after node-red started?
Problems like this wouuld have been easier to track down that way.

I'll try adding ESLINT to VS Code though, hope that'd help.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.