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?
Assuming this code :
Now if you have this :
It is specified by the standard that the
contextparameter ofmyCallbackwill beuniqueContextat the moment where the callback will be fired. It can cause some issues when you try something like this in a loop (because you will eraseuniqueContextat each iteration).If you do this :
The callback using
uniqueContext1is garanteed to be called when the firstlongRunningFunctionwill end, and the one usinguniqueContext2when the secondlongRunningFunctionwill end (with the same restriction than before; if you overwriteuniqueContext1oruniqueContext2somewhere in your scope, the callback parameter will change too).Using bind allows you to avoid creating a closure (and the default previously mentioned). The following code is similar to the previous one, except that you will never be able to accidentally change the value of the parameter by overwriting the previous one :
mycallback.bind( null, someParameter )will return a function which, when called, will callmycallbackwithnullasthis(which will fallback towindowlike any regular function) andsomeParameteras first parameter.The other answer is using only the first parameter of
bindbecause they use thethisvariable, but it is not required and you can safely use function parameters instead.