1

I have made up the following example to test asynchronous callback events in node.js. The fact is that the error is not returning me a parameter. Why is that?

var maxtime = 1000;

var evenDoubler = function(v, callback) {
    var waitTime = Math.floor(Math.random() * (maxtime + 1));
    if (v%2) {
        setTimeout(function() {
            callback(new Error("Odd input"));
        }, waitTime);
    }
    else {
        setTimeout(function() {
            callback(null, v*2, waitTime);
        }, waitTime);
    }
}

for (i=1;i<=10;i++) {
    evenDoubler(i, function (error, result, waitTime) {
    if (error){
        console.log(error + " by number " + i);
    }
    else {
        console.log("The number is even, and its double is " + result + " (in " + waitTime + " miliseconds).");    
    }
});   
}

the returned output is (why is returning me the values 11 on the odd numbers?)

Error: Odd input by number 11
Error: Odd input by number 11
The number is even, and its double is 20 (in 266 miliseconds).
The number is even, and its double is 12 (in 444 miliseconds).
Error: Odd input by number 11
The number is even, and its double is 4 (in 492 miliseconds).
The number is even, and its double is 16 (in 578 miliseconds).
The number is even, and its double is 8 (in 710 miliseconds).
Error: Odd input by number 11
Error: Odd input by number 11
Rick
  • 528
  • 1
  • 6
  • 15

1 Answers1

2

It's because your for loop has already completed by the time the first async callback occurs so i is 11 at that point which is why that gets logged for the if (error) path that the odd numbers take.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Ok, yeah. Of course is quite obvious what the 11 number suggests that at that point the loop has already completed. What I wanted to know was the reason for this to happen, since what I expected was a unary increment of the variable and a logging of its actual value for every loop. – Rick Aug 08 '14 at 22:55
  • What I know now is that the reason for this to happen lays in a "not locked i variable for every loop", which is solved (the locking of the variable for every loop) by using IIFEs. – Rick Aug 08 '14 at 22:57