0

I need to retrieve several values from an IndexedDB, check if all of them fulfill some constraint (different for all of them) and if so call a function. To illustrate this better imagine that calls to IndexedDB were sychronous, we would have something like.

function myFunc(varNames, conditions) {
    for(var i = 0; i < varNames.length; i++) {
        if(!isGood(db.get(varNames[i]), conditions[i])) {
            return;
        }
    }
    doStuff();
}

Since IndexedDB is are asynchronous I do not konw how to do it. Using a callback in every get is not really feasible since the call to doStuff depends on all the gets. Accumulating the results in a global variable would not work either because myFunc is called more than one. I tried something like:

function myFunc(varNames, conditions) {
    var valid = 0;
    checker() {
         valid++;
         if(valid == varNames.length) {
             doStuff();
         }
    }
    for(var i = 0; i < varNames.length; i++) {
        db.get(varNames[i], function(val) {
            if(isGood(val, conditions[i]) {
                checker();
            }
        });
    }
}

But that does not seems to work either. Any ideas?

alexmg
  • 3
  • 2
  • See [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) for ideas. tl;dr: Use promises. – Felix Kling May 01 '14 at 12:01
  • Your function declarations must be prefixed with `function`, otherwise you will get a syntax error. – levi May 01 '14 at 15:54

1 Answers1

0

You can make the DB calls one at a time, and use the success callback to make the next DB call. Something like this:

function myFunc(varNames, conditions){
    if(varNames.length){
        var name = varNames.shift(),
            condition = conditions.shift();
        db.get(name, function(val){
            if(isGood(val, condition)){
                myFunc(varNames, conditions);
            }
        });
    } else {
        doStuff();
    }
}
levi
  • 23,693
  • 18
  • 59
  • 73