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);
        });
    }