DEV Community

Dave Scotese
Dave Scotese

Posted on

Do Re-entrant Node.js Functions have Unstable Arguments?

I have code (kraken-grid on github) which makes requests to the Kraken API and awaits the responses. It runs periodically and I noticed that Kraken's API slowed down enough for a second run of the code to happen while the first run was awaiting a response. The code handles TIMEOUT from Kraken by trying again in 5 seconds. It seems to me that a call to order (a function I wrote) from the first run got its arguments clobbered by the second run. It passes an array [first element is a string, second is an object with properties for all the values the API is to use] to kapi() which calls itself again with the same array after waiting five seconds. The result is that when the API (AddOrder) was called the second time (5 seconds after a TIMEOUT response), it used (at least) two argument values that differed from those with which it was first called.

The code can be viewed at https://github.com/dscotese/kraken-grid/blob/main/index.js.

I'm trying to understand how it happened so that I can prevent it. My suspicion is that nodejs creates an internal object for each variable and does not consider the arguments to a function call from one frame of execution to be different than the arguments when it's called from a different frame. I see that three of the passed in arguments are re-assigned (price = Number(price) for example) and the two that are changing are among them. I use the same names but perhaps the interpreter is creating new (implied var) declarations and that is why re-entrant calls alter their values.

I updated the code (not yet in github) so that new variables (let declarations) are used. If someone can confirm that this will most likely prevent the problem (and why), I'd appreciated it!

Top comments (0)