I am using a third-party JavaScript library that has a certain long-running function (it involves web service calls over the network, etc). For simplicity, let's say it takes one parameter, a callback function to call when the long-running operation completes, so let's say we have the signature longRunningFunction(callback)
.
Unfortunately, the function does not accept a "context" parameter, so if I call longRunningFunction
multiple times, when my callback is called I have no way of knowing which call resulted in which callback.
I found the following way to solve this, by using anonymous functions: Define a mycallback(context)
function, and then do something like this every time I invoke the long-running operation:
uniqueContext = getUniqueContextFromSomewhere();
longRunningFunction(function() {mycallback(uniqueContext)});
This seems to work, but my question is whether or not this is guaranteed to work according to the JavaScript spec in all possible circumstances, given that the long-running operation may be executing on a different thread, callbacks to the various calls to longRunningFunction may come in any order, etc. So, is the solution I found valid?