当在javascript中的循环中使用回调时,是否有任何方法来保存在循环中更新的变量以用于回调? [英] When using callbacks inside a loop in javascript, is there any way to save a variable that's updated in the loop for use in the callback?

查看:125
本文介绍了当在javascript中的循环中使用回调时,是否有任何方法来保存在循环中更新的变量以用于回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有如下的东西:

  for(var i = 0; i< length; i ++){ 
var variable = variables [i];
otherVariable.doSomething(variable,function(err){// doSomething结束时的回调
对变量执行别的操作
}
pre>

到调用回调时, variable 将不可避免地成为所有回调的最后一个变量,我认为我可以通过变量 doSomething()然后得到返回作为回调的一部分,但 doSomething()是一个外部库的一部分,我不想乱麻烦的源代码



做那些知道JavaScript的人比我知道是否有其他方法来做我想做的事情?



最好,谢谢,
Sami

解决方案

,处理这种情况的方法是使用立即调用的另一个函数来创建一个作用域来保存变量。

  (var i = 0; i<长度; i ++){
var variable = variables [i];
otherVariable.doSomething(function(v){return function(err){/ * something with v * /};}(variable));
}

请注意,在立即调用的函数内部,正在创建的回调, ,将参数引用到函数 v ,而不是外部变量。为了使这个读取更好,我建议提取的回调的构造函数作为一个命名的函数。

  function callbackFor(v){ 
return function(err){/ * something with v * /};
}
for(var i = 0; i var variable = variables [i];
otherVariable.doSomething(callbackFor(variable));
}


Let's say I have something as follows:

for(var i = 0; i < length; i++){
  var variable = variables[i];
  otherVariable.doSomething(variable, function(err){ //callback for when doSomething ends
    do something else with variable;
  }

By the time the callbacks are called, variable will inevitably be the last variable for all the callbacks, instead of being a different one for each callback, as I would like. I realize that I could pass variable to doSomething() and then get that passed back as part of the callback, but doSomething() is part of an external library, and I'd rather not mess around with the source code for that.

Do those of you that know JavaScript better than I do know if there are any alternative ways to do what I'd like to do?

Best, and thanks,
Sami

解决方案

A common, if ugly, way of dealing with this situation is to use another function that is immediately invoked to create a scope to hold the variable.

for(var i = 0; i < length; i++) {
  var variable = variables[i];
  otherVariable.doSomething(function(v) { return function(err) { /* something with v */ }; }(variable));
}

Notice that inside the immediately invoked function the callback that is being created, and returned, references the parameter to the function v and not the outside variable. To make this read much better I would suggest extracting the constructor of the callback as a named function.

function callbackFor(v) {
  return function(err) { /* something with v */ };
}
for(var i = 0; i < length; i++) {
  var variable = variables[i];
  otherVariable.doSomething(callbackFor(variable));
}

这篇关于当在javascript中的循环中使用回调时,是否有任何方法来保存在循环中更新的变量以用于回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆