I’ve never had to use callback functions before, so I may have made a completely stupid mistake. I think I somewhat understand the problem here, but not how to solve it.
My code (a bit simplified) is:
for (var i = 0; i < some_array.length; i++) {
var title = some_array[i];
$.getJSON('some.url/' + title, function(data) {
do_something_with_data(data, i);
}
Now as far as I understand, this anonymous function will only be called if getJSON() has received the data. But by this point, i does not have the value I would require. Or, as far as my observation goes, it has the last value it would have after the loop is done (shouldn’t it be out of bounds?).
As a result, if the array had a size of 6, do_something_with_data() would be called five times with the value 5.
Now I thought, just pass i to the anonymous function
function(data, i) { }
but this does not seem to be possible. i is undefined now.
You need to understand what a closure is. In JavaScript, there are certain rules about the scope of each variable.
varis the nearest/currentfunction(including "arrow functions"), or if not in a function, then thewindowor other global object appropriate for the execution context (e.g., in Node,global).letorconst(in ES5 and up) is the nearest statement block{ /* not an object, but any place that will take executable statements here */ }.If any code can access a variable in the current scope or in any parent scope, this creates a closure around that variable, keeping the variable live and keeping any object referred to by the variable instantiated, so that these parent or inner functions or blocks can continue to refer to the variable and access the value.
Because the original variable is still active, if you later change the value of that variable anywhere in the code, then when code with a closure over that variable runs later it will have the updated/changed value, not the value when the function or scope was first created.
Now, before we address making the closure work right, note that declaring the
titlevariable withoutletorconstrepeatedly in the loop doesn’t work.varvariables are hoisted into the nearest function’s scope, and variables assigned withoutvarthat don’t refer to any function scope get implicitly attached to the global scope, which iswindowin a browser. Beforeconstandletexisted,forloops in JavaScript had no scope, therefore variables declared within them are actually declared only once despite seeming to be (re)declared inside the loop. Declaring the variable outside the loop should help clarify for you why your code isn’t working as you’d expect.As is, when the callbacks run, because they have a closure over the same variable
i, they are all affected wheniincrements and they will all use the current value ofiwhen they run (which will as you discovered be incorrect, because the callbacks all run after the loop has completely finished creating them). Asynchronous code (such as the JSON call response) does not and cannot run until all synchronous code finishes executing–so the loop is guaranteed to complete before any callback is ever executed.To get around this you need a new function to run that has its own scope so that in the callbacks declared inside of the loop, there is a new closure over each different value. You could do that with a separate function, or just use an invoked anonymous function in the callback parameter. Here’s an example:
For clarity I’ll break it out into a separate function so you can see what’s going on:
Note: since your array apparently only has titles in it, you could consider using the
titlevariable instead ofiwhich requires you to go back tosome_array. But either way works, you know what you want.One potentially useful way to think about this that the callback-creating function (either the anonymous one or the
createCallbackone) in essence converts the value of theivariable into separatethisivariables, via each time introducing a new function with its own scope. Perhaps it could be said that "parameters break values out of closures".Just be careful: this technique will not work on objects without copying them, since objects are reference types. Merely passing them as parameters will not yield something that cannot be changed after the fact. You can duplicate a street address all you like, but this doesn’t create a new house. You must build a new house if you want an address that leads to something different.