Reputation: 1948
I have a list with some items, & a loop in which I check whether each item in the list is found in the database or not (To insert it if it's not found).
function AddItems(tx)
{
for(var i = 0 ; i<itemscounter; i++)
{
itemI=itemsList[i];
tx.executeSql('SELECT * FROM Items Where ItemsTable.ItemId="'+itemI+'"', [], AddItemsToDB, errorCB);
}
}
The problem is that the function waits till it finishes all the iterations then execute the sqlite statement so the itemI value is always equal to itemsList[itemscounter]. So it enters the AddItemsToDB "items counter" times, but always with the same value (the last one in the array).
This is the success Function:
function AddItemsToDB(tx, results)
{
var len = results.rows.length;
alert(itemI); // Always has the same value!
if(len==0)
{
tx.executeSql('INSERT INTO ItemsTable (ItemId) VALUES ('+itemI +')');
}
}
So, I'm wondering if there is some method to pass parameters at the success function itself, or if there is another method to pass the items one by one ?
Upvotes: 3
Views: 2408
Reputation: 48813
Yes , there is.Try something like this:
tx.executeSql('SELECT * FROM Items Where ItemsTable.ItemId="'+itemI+'"', [],
(function(itemI){
return function(tx,results){
AddItemsToDB(tx,results,itemI);
};
})(itemI), errorCB);
And modify AddItemsToDB
like a:
function AddItemsToDB(tx, results, itemI) {
Upvotes: 3