Ensuring Variable Integrity in Async Callback Functions with JavaScript Closures.

Callback functions to asynchronous requests may need to reference variables outside of itself. This can be problematic because those variables might not maintain the values you expect by the time the callback function fires. In the past I’ve dealt with this by writing my code as a string, concatenating my variable values, then using eval on it in the callback. I never liked this technique because it seemed amateur, risky and unreliable for complex scenarios. Recently I came across a clever solution that seems to work quite well:
Here we wrap a function around the code, and execute it immediately passing the target variables into it. In my example the variables are file and uploader. Next, we then have an inner function that keeps the meat of our code from being executed immediately. It will be executed in the callback of the asynchronous process…but can reference the variables passed to it’s wrapper function. In the example I have used the same variable names again (no need to change them). I believe the technique duplicates the variables into a local scope where its values can be maintained. This is also known as a JavaScript Closure where functions have access to private variables that nothing else can touch or modify.

Here is a FIDDLE showcasing the technique. Enjoy.