当在 javascript 循环中使用回调时,有什么方法可以保存在循环中更新的变量以便在回调中使用?
假设我有如下内容:
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;
}
当调用回调时,variable
将不可避免地成为所有回调的最后一个变量,而不是像我希望的那样,每个回调都是不同的变量。我意识到我可以将 variable
传递给 doSomething()
,然后将其作为回调的一部分传回,但 doSomething()
是一部分外部库的,我不想弄乱它的源代码。
你们中那些比我更了解 JavaScript 的人是否知道是否有其他方法可以完成我想做的事情?
最好的,谢谢,
萨米
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
处理这种情况的一种常见(虽然丑陋)方法是使用另一个立即调用的函数来创建一个范围来保存该变量。
请注意,在立即调用的函数内部,正在创建并返回的回调引用函数
v
的参数,而不是外部变量
。为了更好地阅读,我建议将回调的构造函数提取为命名函数。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.
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 outsidevariable
. To make this read much better I would suggest extracting the constructor of the callback as a named function.好吧,我似乎已经弄清楚了。我需要做的是在
otherVariable.doSomething()
周围放置一个function(var)
包装器,因此更新后的代码如下所示:希望这可以帮助其他人以后还会遇到类似的事情!
@aparker42,我仍然很想在你的问题的评论中听到你对我的问题的回答,因为这仍然让我感到困惑。
编辑:当然,因为这是 javascript,你不会想使用
var
作为变量名。Ok I've seemed to figure this out. What I needed to do was to put a
function(var)
wrapper aroundotherVariable.doSomething()
, so the updated code looks as follows:hope this helps anybody else that gets stuck on something like this in the future!
@aparker42, i'd still love to hear your answer to my question in the comment to your question, since that still does confuse me.
EDIT: of course, since this is javascript, you wouldn't want to use
var
as a variable name.