0

This might be a silly question. Below is a stripped down version of my code.

for (var i = 0; i < objects.length; i++) { // objects.length = 10
    CuQuery.count().then(function(result){
      Cucount = result;
      console.log("i value = "+i);
    }, function(error) {
        response.error(error);
    });
}

In console, I get i value = 10, 10 times as output. I expected it to print value 1 to 10. What am I doing wrong ? or Is it the correct behavior ?

Sajan
  • 1,893
  • 2
  • 19
  • 39
  • 1
    It is correct behavior, that is how async works – Ananth Apr 20 '17 at 12:23
  • Your passed function will be called a long time (some ms) after the iteration is done. At this moment ```i``` has the value`= 10. This behaviour is totally correct. – Frank Roth Apr 20 '17 at 13:11
  • Promises within loops is very tricky, in my opinion better use `async.map` or `async.mapSeries`. – Frank Roth Apr 20 '17 at 13:12
  • Thanks Ananth and Frank Roth for the clarification. Answers from the the original question (of which it is a duplicate) helped a little understand the problem. – Sajan Apr 20 '17 at 13:34

0 Answers0