Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

javascript - webkit executesql sentence and loop problem

I'm trying to use loop variable in executeSql function that contained by loop. But loop variable gets the last value if i don't use a closure. When i use a closure , i don't get the result list from executeSql function. Examples:

for (var i = 0; i < count; i++) {
tx.executeSql('SELECT AColumn FROM ATable WHERE refID=' + i, [],
function(tx,results) //success function
{
//do something
}
,errorfunction);

}

In success function "i" is always "count+1".

To solve this i changed my code like this:

for (var i = 0; i < count; i++) {
tx.executeSql('SELECT AColumn FROM ATable WHERE refID=' + i, [],
(function(tx,results) //success function
{
//do something
})(i)
,errorfunction);
}

With this, i get the "i" right. But "results" is undefined.

I tried to pass "tx" and "i" like this:

    (function(tx,results) //success function
    {
    //do something
    })(tx,null,i)

With this i understand why i get "results" as null. I want to learn how can i get the right results of executeSql.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're looking for the following:

for (var i = 0; i < count; i++) {
   tx.executeSql('SELECT AColumn FROM ATable WHERE refID=' + i, [],
      (function(i){
         return function(tx,results) //success function
         {
            //do something
         };
      })(i),
   errorfunction);
}

At the end of the day you need to pass a function of the signature function(tx,res) which is clearly what that whole (function(i){ return function(tx,res){ ... }; })(i) does, since the outer anonymous function executes immediately and returns a function of that signature.

The value i in that inner function has the value of i when the outer function was called (i.e. the value of each iteration), since the value i is passed by value into the outer anonymous function, so references to i in the returned inner function will resolve correctly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...