In a loop I'm calling an outer function to which I'm passing two arguments(say arg1 and arg2) from the calling function. The arguments' value will be different on every iteration. The outer function will use arg1 to call an API. So there will be as much calls to the API as that of the number of loop iterations. After each of the API request is complete and the value is returned to the API's handler, I'm trying to use the result along with the 2nd arg to perform some function. The problem is that, the value of 2nd arg is always the value which is passed at the last iteration from the calling function. Instead I would expect the appropriate values to be bound to the API handler.
I used closures, inline closures calling an outer function to hold the handler (explained above)
1]
var array = [ ... ]; // An array with some objects
function callbackClosure(i, callback) {
return function() {
return callback(i);
}
}
for( var i = 0; i < array.length; ++i )
{
API.doSthWithCallbacks( callbackClosure( i, function(i) {
array[i].something = 42;
}) );
}
2]
var array = [ ... ]; // An array with some objects
for( var i = 0; i < array.length; ++i )
{
API.doSthWithCallbacks( (function() {
var j = i; // j is a copy of i only available to the scope of the inner function
return function() {
array[j].something = 42;
}
})() );
}
from --> https://www.pluralsight.com/guides/javascript-callbacks-variable-scope-problem
_gotName(a_uri, a_query){
API.(a_uri, {handler : function(a_result, a_callBckObj){
console.log(a_callBckObj.data.queryInst.seqNum);
}, data : {queryInst : a_query}});
},
//calling function
_gotLog(a_qry){
var uri;
do {
uri = a_qry.queryUri("/uri");
this._gotName(uri, a_qry);
} while (a_qry.gotoNext());
}
Expected: 1 2 3 4 Actual; 4 4 4 4