-1

I am unable to access the value of the variable "k" inside the function "Success" but outside it, it's showing the correct value and also the contents of the array are not being retained inside the same function.

The value of k in the logs is always equal to the nArray.length, which is the condition for my FOR loop.

Is this a problem with Parse.com's cloud code, or is there a problem with my code?

Thanks for reading.

nArray = gameScore.get("myArray");
var query2 = new Parse.Query("User");    
for (var k=1; k < nArray.length; k++) {
  query2.equalTo("username", nArray[k]);
  query2.find({
    success: function(results) {
      if (results.length !== 0) {
        **alert("The value of k is" + k);** //the value of k here always is equal to the total # of loops
        var object = results[0];
        alert(object.id + ' - ' + object.get('email'));
        var ema = object.get('email');
        mArray.push(ema);
        alert("Matched Contacts:" + mArray.length);
      }
    },
    error: function() {
      response.error("movie lookup failed");
    }
  });
  alert(mArray.join('\n'));
  alert("The value of k at bottom is correct" + k);
};
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
Alik Rokar
  • 1,135
  • 1
  • 10
  • 16

1 Answers1

2

The problem is that find get k when the loop ended so k has the value of the last iteration. You could use a closure like this

nArray = gameScore.get("myArray");
var query2 = new Parse.Query("User");

for (var k=1; k < nArray.length; k++)
{
    (function(k){ // <-- define an inline function
        query2.equalTo("username", nArray[k]);
        query2.find({
            success: function(results) {

                if (results.length !== 0)
                {
                      alert("The value of k is" + k);
                      var object = results[0];
                      alert(object.id + ' - ' + object.get('email'));
                      var ema = object.get('email');
                      mArray.push(ema);
                      alert("Matched Contacts:" + mArray.length);

                }
            },
            error: function() {
              response.error("movie lookup failed");
            }
        });
    })(k); // <-- call it after definition using (k)
    alert(mArray.join('\n'));
    alert("The value of k at bottom is correct" + k);
};

I'm assuming that parameters of find are callbacks executed async, otherwise I can't explain the behavior you report.

If this is the case, take into account that mArray.join('\n') won't work as you expect.

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155