I have:
for (var i=0;i<2;i++) {
dbo.transaction(
function(myTrans) {
myTrans.executeSql(
'UPDATE myTable SET myField=0 WHERE myID=?'
,[i]
)
}
)
}
Because the function is a callback, it is being called with i=2.
Q: How do I call it with i=0 and i=1?
Note: I think that’s what is happening. I think I’ve stated the problem correctly (that it’s caused because the callback executes after the loop is finished).
You’re probably right about what the bug is. The solution to this is to wrap an anonymous function around the inside of the loop, which holds a new and unchanging
ivariable for the enclosed code to see.ECMAScript Harmony (the proposal for the next version of JavaScript) includes a new keyword,
let, which will make a bit cleaner. It will work like this:It might even be possible to just replace
var iwithlet i, but as far as I know consensus hasn’t yet been reached on this point.