向回调函数添加其他参数 [英] Add additional parameters to callback function

查看:502
本文介绍了向回调函数添加其他参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Node.js中构建一个系统,它应该找到文件夹数组中的所有文件,对它们进行统计,然后使用该信息做一些额外的工作。

I'm building a system in Node.js that is supposed to find all files in an array of folders, stat them, and then do some additional work using that information.

我正在使用fs.readdir()从每个文件夹中同步获取所有文件。我的代码如下所示:

I'm using fs.readdir() to get all the files synchronously from each of the folders. My code looks like this:

for(i=0,max=paths.length; i<max; i++) {
    var path = paths.pop();
    console.log("READING PATH: " + path);
    fs.readdir(path, function(err, files) { handleDir(err, files, path); });
}

问题在于,取决于readdir()执行的速度,handleDir ()正在走错路。发生这种情况是因为在回调运行时,下一个循环已经开始 - 意味着路径变量已经改变。

The problem is that, depending on how fast the readdir() executes, handleDir() is getting the wrong path. This happens because by the time the callback runs, the next loop has already started - meaning that the path variable has changed.

所以,我需要做的就是以某种方式锁定该路径变量为其特定的回调函数。我想不出有什么好方法可以做到这一点 - 任何人都有一些想法?

So, what I need to do is somehow lock that path variable to it's specific callback function. I can't think of any good way to do this - anyone have some ideas?

推荐答案

没有块范围,所以使用函数作为范围。

There is no block scope, so use a function for scope.

for(var i=0, path, max=paths.length; i<max; i++) {
    path = paths.pop();
    console.log("READING PATH: " + path);
    handlePath( path );
}
function handlePath ( path ) {
    fs.readdir(path, onPathRead);
    function onPathRead (err, files) {
        handleDir(err, files, path);
    }
}

这篇关于向回调函数添加其他参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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