1

I am trying to populate a database using a for loop for one of the database values using persistenceJS (http://persistencejs.org)

The problem I'm having is that when I do alert(i) and then do a persistenceJS call, both the alerts are shown before the persistenceJS is run.

The code below explains a bit better

    for(var i = 0; i < 2; i++) {

        alert(i); //0 and 1 are alerted then the below runs

        Answer.all().count(function(co) {
            alert('current count is:' + co); //alerts 0
    });
    }

Above is some test code that shows the problem, below is the code I will actually be using.

Answer = persistence.define('Answer', {
 level: "INT",
 image: "INT",
 correct: "INT",
 hints: "INT"
});

 persistence.store.websql.config(persistence,'FootballQuiz', 'Storage of answer status', 5 * 1024 * 1024);
 persistence.schemaSync();

for(var i = 0; i < 2; i++)
//checks to see if the current value exists in the db
Answer.all().filter('level', '=', 1)
            .and(new persistence.PropertyFilter('image', '=', i))
            .count(function(c){
                if(c > 0) {
                    alert('already exists');
                } else {
                    var tmpAnswer = new Answer();
                    tmpAnswer.level = "1";
                    tmpAnswer.image = i;
                    tmpAnswer.correct = "0";
                    persistence.add(tmpAnswer); 
                    persistence.flush();
                }
            });
}

I would like the persistenceJS to execute each loop. Thanks

SkelDave
  • 1,176
  • 2
  • 9
  • 23
  • 1
    You need to use a closure -- loops will finish before any of the dynamic functions get called. There are lots of questions like this on SO -- search for loop + closure + javascript – Hogan Apr 04 '13 at 16:06
  • 1
    Duplicate: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – freakish Apr 04 '13 at 16:11

0 Answers0