1

Why i cant access 'i' variable in transaction? console.log(data); outputs data successfully. console.log(data[i]); says undefined..

            for(var i = 0; i < data.length ; i++){
            db.transaction(function(tx){
                console.log(data);
                console.log(data[i]);
                tx.executeSql('SELECT * FROM REGISTERED_EVENTS where EVENT_ID = ?', [data[i].id], function(tx, results){
                   //do something
                }); 
            });
        }
AhmetZG
  • 11
  • 3

1 Answers1

1

Why i cant access 'i' variable in transaction?

You can, but it won't have the value you expect. The transaction callback is called later, when the loop has been completed. That callback has an enduring reference to the variable i, not a copy of its value when the callback was created, and so it sees i with the value data.length. And so you get undefined for data[i].

For this situation, I usually use a builder function so the callback closes over a variable that doesn't change:

for (var i = 0; i < data.length; i++) {
    db.transaction(buildHandler(i));
}
function buildHandler(index) {
    return function(tx) {
        console.log(data);
        console.log(data[index]);
        tx.executeSql('SELECT * FROM REGISTERED_EVENTS where EVENT_ID = ?', [data[index].id], function(tx, results) {
            //do something
        });
    };
}

That works because the function that buildHandler creates keeps a reference to index, and index is never changed.

Or, in that specific situation, you could get good use out of Array#forEach, because it already gives you a variable (well, an argument) that won't change:

data.forEach(function(entry, index) {
    db.transaction(function(tx) {
        console.log(data);
        console.log(data[index]);
        tx.executeSql('SELECT * FROM REGISTERED_EVENTS where EVENT_ID = ?', [data[index].id], function(tx, results) {
            //do something
        });
    });
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875