Logic in nodered function to lock or release

In my code I have 10 place when I make http request to 10 diffrent resource on the same server. But http server of that resource allow only 1/request per client per 3 seconds. How to make this on node-red?. I prefer logic in javascript function block.

My first solution was to create in function while loop and in that loop check global variable (e.g myLock). If myLock is false then set it to true, make request, wait 3 second, set myLock to false and return value.
This solution is not elegant but I'm thing that will work. But I dont now is context variable is safe in this situation ? What you think about this?

Best regards

Welcome to the forum @zygfrydos

Feed the requests through a Delay node set to Rate Limit mode set to 3 messages per second or less.

That would block the nodejs event loop. (nodeJS and therefore Node-RED is single threaded, event loop driven) In short, looping i a function is bad (and anti-pattern)

function block is not ideal for this.

A better solution:

Create a subroutine consisting of link-in -> delay node (rate limit mode) -> http request -> link-out (set to return mode)

then, whenever you need to call to HTTP, use a link-call node. It will add your request to the queue and return to you when it is done.

image

Thank you Steve-Mcl.
This is good solution for now and solving my problem.
However, if I wanted in future write this in my own node in javascript. How to safe semaphore/variable and execute some code if this variable change?

Do you mean as a node package (like node-red-contrib-my-super-duper-node) - OR - as a function node in the editor?

I mean package. I now that function node is in sandbox and it's slow but safe :slight_smile:

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