Scenario:
Get () and set () are two asynchronous functions. In a for loop, I first get data and then set data.
The following code displays the following situations:
- for(var i=1;i<=1000;++i){
- var res = get("args"+i,function(err,data){
- set("args"+i,data,function(err,result){});
- })
- }
The above code will show this situation: when the set function is executed, I has changed to 1001. Why?
My personal understanding: Asynchronization does not wait, because the efficiency of the loop is higher than that of Asynchronization, so when it is set execution, I has changed to 1001;
How can this problem be solved?
I was so stupid at the time that I took my own services and wrote down it here to despise myself in the future:
- for(var i=1;i<=1000;++i){
- var res = get("args"+i,function(err,data){
- for(var i=1;i<=1000;++i){
- set("args"+i,data,function(err,result){});
- }
- });
- }
This is the case, but the set function has been executed for 1000*1000 times, and you have come up with this method.
After correction, I want to define a global variable and then set the function without using I.
- var j=1;
- for(var i=1;i<=1000;++i){
- var res = get("args"+i,function(err,data){
- set("args"+(j++),data,function(err,result){});
- });
- }
This is a solution, but it is not perfect. First, it is always bad to define a global variable. In addition, some people will inevitably see this code saying that I and j are not the same? Unless you comment out the previous sentence, who will remove this global j and I will be desperate.
So I thought of this method again:
- for(var i=1;i<=1000;++i){
- (function(idx){
- var res=get("args"+idx,function(err,data)
- set("args"+idx,data,function(err,result){});
- });
- })(i);
- }
To solve the problem of not defining a global variable externally, the anonymous function does not use the "Global" variable at all, which is much better.