Question

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?

Was it helpful?

Solution

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();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top