0

I am working with Parse API (parse.com), and I am having a lot of trouble integrating a function into a for loop. I am trying to pass down the for loop variable "k" into the function, but it won't seem to work. I can't seem to access the "k" variable down under the parse success function. Can someone please help me?

Here is my code:

function checkStock () {
    for(k=0; k<productNum; k++) {

        var usersID = parseJson.Products[k].userID;

        var NikeLogins = Parse.Object.extend("NikeLogins");
        var query = new Parse.Query(NikeLogins);
        query.get(usersID, {
            success: function(NikeLogins) {
                var score = NikeLogins.get("inStock");
                if (score == false) {
                    alert(k);
                }
            }
        });
    }
}
Robert Christopher
  • 461
  • 1
  • 6
  • 15
  • Is this always showing k to be productNum's value this is probably because you are capturing k in a loop where you are defining a function. – t3dodson May 22 '15 at 00:42

1 Answers1

0

You have to close around it with another function.

function checkStock () {
    for(k=0; k<productNum; k++) {
        (function(k) {
          var usersID = parseJson.Products[k].userID;

          var NikeLogins = Parse.Object.extend("NikeLogins");
          var query = new Parse.Query(NikeLogins);
          query.get(usersID, {
              success: function(NikeLogins) {
                  var score = NikeLogins.get("inStock");
                  if (score == false) {
                    alert(k);
                  }
              }
          });
        })(k);
    }
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445