简体   繁体   English

将javascript参数从外部范围传递到匿名回调函数

[英]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. 我希望secondFunction被异步调用10次,每次接收到一个以num为单位的不同数字。 Instead, secondFunction is called 10 times and in all of them num is 10. 而是,secondFunction被调用了10次,总共num是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. 您同步for循环增值i一路前10名第一FB.api异步回调执行。

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. 该修复程序将异步函数调用放入其自己的函数中,以便可以将i作为参数传递,在调用时而不是在发生异步回调时捕获i的值。

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. 这是因为仅当服务器返回异步调用的响应并且服务器继续响应var I时,循环才继续运行时,才调用第二个函数。

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. 要修复它,您需要能够将i变量传递到第一个api并将其传递给第二个api的音调,以便您进行引用。

You may have to refactor the method to get them to loop 10 times 您可能必须重构该方法才能使它们循环10次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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