开发者

How to work with an asynchronous database

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开发者_如何学Go 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).


Use anonymous function to capture the variable:

for (var i=0;i<2;i++) {
    (function(i){
        dbo.transaction(
            function(myTrans) {
                myTrans.executeSql(
                    'UPDATE myTable SET myField=0 WHERE myID=?'
                    ,[i]
                )
            }
        )
    }(i));
}


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 i variable for the enclosed code to see.

for (var i=0;i<2;i++) {
    (function(i) {
        dbo.transaction(
            function(myTrans) {
                myTrans.executeSql(
                    'UPDATE myTable SET myField=0 WHERE myID=?'
                    ,[i]
                );
            }
        );
    })(i);
}

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:

for (var i=0;i<2;i++) {
    let (i = i) {
        dbo.transaction(
            function(myTrans) {
                myTrans.executeSql(
                    'UPDATE myTable SET myField=0 WHERE myID=?'
                    ,[i]
                );
            }
        );
    }
}

It might even be possible to just replace var i with let i, but as far as I know consensus hasn't yet been reached on this point.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜