Possible Duplicate:
javascript: Using the current for-loop counter-value inside a function() { }?
If I run the code below, the second console log output merely repeats the last line of the first console log output.
This I understand is because all the nested Query 2’s are queued to run after everything else has completed. Also as we have a function within a function, this creates a ‘closure’ which means there is only one set of variables for the nested Query 2’s and it’s the final state of these that is used, hence only the results for last Query 1 are used repeatedly for the Query 2. At least I think this is what is happening. The question is, how can I change it so that the whole thing works sequentially?
Thanks!
db.transaction(function(tx){
// Query 1
tx.executeSql("SELECT * FROM Products GROUP BY ssrt55", [], function(tx, listResults){
for (var i = 0; i < listResults.rows.length; i++) {
var lineData = listResults.rows.item(i);
var productDescriptionSQL = "select * from ProductDescriptions where bsrt56 = " + lineData['SSRT55'];
console.log(productDescriptionSQL);
// Query 2
tx.executeSql(productDescriptionSQL, [], function(tx, descriptionResults){
console.log(productDescriptionSQL);
}, onError);
}
}, onError);
});
First console log output select * from ProductDescriptions where bsrt56 = 1.00 select * from ProductDescriptions where bsrt56 = 2.00 select * from ProductDescriptions where bsrt56 = 2.50 select * from ProductDescriptions where bsrt56 = 3.00 select * from ProductDescriptions where bsrt56 = 4.00 Second console log output select * from ProductDescriptions where bsrt56 = 4.00 select * from ProductDescriptions where bsrt56 = 4.00 select * from ProductDescriptions where bsrt56 = 4.00 select * from ProductDescriptions where bsrt56 = 4.00 select * from ProductDescriptions where bsrt56 = 4.00