在 JavaScript 的 for 循环中调用异步函数

编程入门 行业动态 更新时间:2024-10-27 08:35:08
本文介绍了在 JavaScript 的 for 循环中调用异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下代码:

for(var i = 0; i < list.length; i++){ mc_cli.get(list[i], function(err, response) { do_something(i); }); }

mc_cli 是与 memcached 数据库的连接.可以想象,回调函数是异步的,因此它可能会在 for 循环已经结束时执行.此外,当以这种方式调用 do_something(i) 时,它总是使用 for 循环的最后一个值.

mc_cli is a connection to a memcached database. As you can imagine, the callback function is asynchronous, thus it may be executed when the for loop already ended. Also, when calling in this way do_something(i) it always uses the last value of the for loop.

我尝试用这种方式关闭

do_something((function(x){return x})(i))

但显然这总是使用for循环索引的最后一个值.

but apparently this is again using always the last value of the index of the for loop.

我也尝试在 for 循环之前声明一个函数,如下所示:

I also tried declaring a function before the for loop like so:

var create_closure = function(i) { return function() { return i; } }

然后调用

do_something(create_closure(i)())

但同样没有成功,返回值始终是 for 循环的最后一个值.

but again without success, with the return value always being the last value of the for loop.

谁能告诉我我在关闭闭包时做错了什么?我以为我理解它们,但我不明白为什么这不起作用.

Can anybody tell me what am I doing wrong with closures? I thought I understood them but I can't figure why this is not working.

推荐答案

由于您正在运行一个数组,您可以简单地使用 forEach 提供列表项和回调中的索引.迭代将有自己的范围.

Since you're running through an array, you can simply use forEach which provides the list item, and the index in the callback. Iteration will have its own scope.

list.forEach(function(listItem, index){ mc_cli.get(listItem, function(err, response) { do_something(index); }); });

更多推荐

在 JavaScript 的 for 循环中调用异步函数

本文发布于:2023-11-30 18:05:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651010.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!