Re: [persistence.js] Looping

78 views
Skip to first unread message

Zef Hemel

unread,
Apr 5, 2013, 3:54:07 AM4/5/13
to persis...@googlegroups.com
Yes, this is intrinsic to the way asynchronous programming works. There's a brief discussion of the "problem" in the README. The way you can do these things is using the asynchronous versions of forEach that are provided in persistence.js itself:

// First prepare an array with the values we want to iterate over:
var items = [];
for(var i = 0; i < 2; i++) {
   items.push(i);
}

// Now, iterate over it asynchronousl
persistence.asyncForEach(items, function(i, next) {
   // This function will be called for each item in the array, when we're done processing it we call next()
   alert(i);
   Answer.all().count(function(co) {
     alert('current count is:' + co);
     // We're done now, let's move on to the next item in the array
     next();
   });
},
function() {
   // This function is called when all items have been processed
   alert("All done!");
});

HTH

-- Zef


On Thu, Apr 4, 2013 at 5:54 PM, david skelton <dave...@gmail.com> wrote:

Hi, I am trying to populate a database using a for loop for one of the database values using persistenceJS

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();

//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 = lvl;
                    tmpAnswer.image = i;
                    tmpAnswer.correct = "0";
                    persistence.add(tmpAnswer); 
                    persistence.flush();
                }
            });

I would like to make it so the persistentJS runs each loop of the for loop. Thanks

--
You received this message because you are subscribed to the Google Groups "persistence.js" group.
To unsubscribe from this group and stop receiving emails from it, send an email to persistencej...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages