Node.js 中的 For 循环和异步回调?
我是 JavaScript 和 Node.js 新手。我想循环遍历一个目录并将所有文件统计(不是其他目录)添加到一个数组中。正如您在下面看到的,我的代码存在问题,因为回调可能会在 for 循环完成后被调用,因此在回调方法中使用“i”变量将不起作用。但是代码应该是什么样子才能让下面的代码片段起作用呢?和闭店有关系吗?
感谢您的帮助!
fs.readdir(SYNCDIR, function(err1, files) {
var filesOnly = [];
if(!err1) {
for(var i = 0; i < files.length; i++) {
var imgFilePath = SYNCDIR + '/' + files[i];
fs.stat(imgFilePath, function(stat){
if (stat.isFile()){
filesOnly[i] = stat; // This will not be correct since the for-loop has finished
}
});
}
}
});
I'm new to JavaScript and to node.js. I want to loop through a directory and add all file stat (not other directories) to an array. As you see below there is a problem with my code since the callback will probably get called after the for loop has finished so using the "i"-variable in the callback method will not work. But how should the code look so that the below snippet works? Does it have something to do with closures?
Thanks for help!
fs.readdir(SYNCDIR, function(err1, files) {
var filesOnly = [];
if(!err1) {
for(var i = 0; i < files.length; i++) {
var imgFilePath = SYNCDIR + '/' + files[i];
fs.stat(imgFilePath, function(stat){
if (stat.isFile()){
filesOnly[i] = stat; // This will not be correct since the for-loop has finished
}
});
}
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您关于需要使用闭包的说法是正确的。您应该将
for
循环的内容包装在自调用函数中,以保留每次迭代的i
值。You are right about needing to use a closure. You should wrap the contents of the
for
loop in a self-invoking function to preserve the value ofi
for each iteration.一种方法是重写循环的内部结构以使用闭包:
一个更好看的示例,使用 Array.prototype.forEach 实现相同的效果:
One way is to rewrite the innards of the loop to use a closure:
A better looking example, achieving the same, using Array.prototype.forEach:
或者使用新的线程模块( https://github.com/robtweed/Q-Oper8 )然后您可以在线程子进程中使用标准同步编码更简单地完成所有这些工作,因为它们一次只处理一个用户的请求。
告别异步逻辑和嵌套回调!
Alternatively use the new threads module ( https://github.com/robtweed/Q-Oper8 ) and then you can do all this stuff much more simply using standard synchronous coding within the threads child processes, since they only deal with one user's request at a time.
Goodbye to async logic and nested callbacks!