Proper async await usage in function nodes

This forum reply (to a similar question) seems to imply that a naked await should work within a function node...

The call is asynchronous and returns a promise so you need to await for that to complete before you return

This SO post (upper snippet) offers a pattern, which causes my flow to break when I return msg; (no downstream execution or output).

(async function() {
  let res = await pool.query('select 1 as somethingForExample;');
  msg.payload = res;
  return msg;

(...based on the code snippet for querying Postgres here)

Checking node version in node-red I am using...

docker run --rm -it --entrypoint /bin/sh nodered/node-red:1.3.5-minimal
node -v

The version of node is...

Which according to this SO, the minimum required version for an assumed top level async (with which an await could be included) seems to be v13.

Can I let x = await something(); in a function node? Do I need to wrap it in an async? How do I do so successfully given the pattern offered? Does this announcement by the node-red team that flows were transitioned to asynchronous (vs async, specifically) in v1.0 impact this issue?

That code doesn't work because the return statement returns from the wrapping function you've added. It doesn't return back to Node-RED. To send a message from inside a function, you'd use node.send(msg).

But there is no need to use that pattern in the function node. You can use async at the top level inside the node.

// Assume you're getting pool from somewhere...

let res = await pool.query('select 1 as somethingForExample;');
msg.payload = res;
return msg;

Use it, as in, as your example literally illustrates (async isnt written and is assumed to be present)? Or, I would have to include it somewhere (presumably above the // Assume... block you provided)?

Ah-ha! I now see the reference to node.send in the docs, thanks for that clarification!

Still hoping for feedback on intended placement/usage/assumptions for async

If you needed to use the word async anywhere, I would have said so.

I suggest you just try it and see.

I did initially and am troubleshooting some (other, apparently) buggy behavior. Thanks a million for helping rule that out as a cause. Greatly appreciated!

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