views:

54

answers:

2

Pretty sure the answer to this question is "closures" but I'm having a hard time getting it right. Given the following:

     var total = 0;
     db.readTransaction(function (tx) {
     tx.executeSql('SELECT COUNT(id) AS mytotal FROM sometable', [], function (tx, results) {
         total =results.rows.item(0).mytotal;
            console.log(total);
        });
    });

    console.log(total);

The first log statement will log the correct count but the second will log 0. Pretty sure a closure is the answer but ... how?

A: 

First when you set the total you are overwriting its value, but if you change that and not word, try this:

 var total = 0;
 db.transaction(function (tx) {
    (function (_tx){
      _tx.executeSql('SELECT COUNT(id) AS mytotal FROM sometable', [], function (_tx, results) {
        var partial = results.rows.item(0).mytotal;
        console.log(partial);
        total += partial;
      });
    })(tx);
  });

console.log(total);

This way maybe will work, since now you have a local copy of tx to perform the sql execution.

madeinstefano
thanks madeinstefano, didn't work :(
Keith Fitzgerald
A: 

Found (an) answer, feel free to improve:

var total = new Array();
db.readTransaction(function (tx) {
    tx.executeSql('SELECT COUNT(id) AS mytotal FROM sometable', [], function (tx, results) {
        total.push((function (total){doSomethingWithTotal(total)})(results.rows.item(0).mytotal));
    });
});

total.pop(); //executes queued function outside transactional scope
Keith Fitzgerald