0

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

NIV
  • 458
  • 4
  • 19
  • 1
    Try to never use `var` if you can help it, use `const` or `let` instead, `var` has too many gotchas. Your `var j = i;` will be referring to the `i` after the last iteration – CertainPerformance Jul 09 '19 at 06:46
  • Just use `for (let i = 0; i < array.length; i++) { /* do stuff with i */ }`, with block scope, much less complicated, and is guaranteed to work. Or, even better, avoid `for` loops entirely, they're verbose and error-prone, consider `forEach` instead – CertainPerformance Jul 09 '19 at 06:53

0 Answers0