0

There is a different behaviour between Internet Explorer and Google Chrome for when using async callbacks. For this function I load data from the server with a for-loop for the year 2017 until the current year.

The code I have is:

        for (var y = 2017; y <= crrntYr; y++) {
            cnt++;
            var rtrn = evalExpression(sssn, "call('rp/ajax/wkChrt','" + y + "')", function (data) {
                    console.log(y);
                });
        }

The problem exists in Internet Explorer, when the callback is done: y == 2019 So for every year when the data is retrieved, the for loop is already ended and y=2019.

In Google Chrome it works as intented, when the callback is done, y is the value of when the evalExpression() was started, so it is the year is is processing.

How can I set y to the right value in the callback function?

Edit 10:42: Simplified the function to the basics

Jim
  • 3
  • 2

2 Answers2

0

I think you should use let instead of var. See the difference between these two loops:

for (var i = 0; i < 10; i++) {
  // Simulet async call...
  setTimeout(function(){
    console.log(i);
  }, 2000);
}

for (let i = 0; i < 10; i++) {
  // Simulet async call...
  setTimeout(function(){
    console.log(i);
  }, 2000);
}

The first will write 10 in the console 10 times. The second will write 1-10.

You can read about this in this post detailed:

Asynchronous Process inside a javascript for loop

standby954
  • 209
  • 1
  • 7
  • I have the same problem with let (I used let before I changed it to var) It seems that iexplore does not understand let in a for loop, as I found in this article: https://kangax.github.io/compat-table/es6/ But the link you posted also describes a work arround that I will try: Create Your Own Function Closure Using an IIFE Thank you! – Jim Mar 12 '18 at 13:02
0

Found the answer in the post linked by standby954: Create Your Own Function Closure Using an IIFE

        for (let y = 2017; y <= crrntYr; y++) {
            (function(yr) {
                cnt++;
                var rtrn = evalExpression(sssn, "call('rp/ajax/wkChrt','" + yr + "')", function (data) {
                    rCnt++;
                    console.log(yr);
                });
            })(y);
        }
Jim
  • 3
  • 2