This is really getting me:
for(var i=0; i<10; i++) {
(function(x) { //use a closure to hold the "i" value
request(arg[x], function(n) {
//do something with the data returned from $getJSON
console.log(n);
});
})(i) //is this syntax correct?
}
function request(argX, callback) { //is this syntax correct?
$getJSON(parameter) {
//get request result
...
}
callback(); //after request() function is completed, trigger the callback function
//is this syntax right?
}
The reason I am using the callback function is because I want to manipulating the result from getJSON, so I need to wait the request function to complete.
I also need to bound the callback function with the loop index “i” value.
I have played the syntax for quite a while, but how come nothing was returned from the console log? It seems the callback function was never executed or executed before $getJSON was completed.
I need expert’s help!
The
getJSONcall is asynchronous, so you would be calling thecallbackfunction before the response has arrived.Also you have a code bloack after the call to
getJSON. The code in that won’t get called after the result has arrived either, it’s just a separate block that runs after the call, and also before the result arrives.Put the callback function as a parameter in the call to
getJSON: