简体   繁体   中英

Passing a javascript parameter from an outer scope to an anonymous callback function

Consider the following

function firstFunction() {
  for ( var i = 0; i < 10; i++) 
    FB.api(apiPath,function(response) {
      secondFunction(response,i);
  });
}

function secondFunction(response,num) {
  alert(num);
}

I wanted the secondFunction to be called asynchronously 10 times, each time receiving a different number in num. Instead, secondFunction is called 10 times and in all of them num is 10.

Can someone explain to me why it is not passed like i expect and how i can fix it to act like i expect ?

Thanks

Your synchronous for loop increments i all the way to 10 before the first FB.api async callback executes.

Like this:

function firstFunction() {
  for ( var i = 0; i < 10; i++) {
    (function(i2) {
      FB.api(apiPath,function(response) {
        secondFunction(response, i2);
      });
    })(i);
  }
}

The fix puts the async function call into its own function so that i can be passed in as a parameter, capturing the value of i at the time of the call, rather than when the async callback occurs.

This is because the second function is only called when the server returns a response on the asynchronous call and the loop continues running, by the time the server responds the var I is already at 10.

To fix it, you need tone able to pass the i variable into the first api and then have it passed to the second So you can referenced.

You may have to refactor the method to get them to loop 10 times

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM