Javascript Multiple path.exists回调,如何知道返回状态是针对哪个文件的?
用于检查文件是否异步存在的node.js内置库函数仅向回调提供布尔值“exists”。我需要检查是否存在多个似乎有问题的文件。我如何知道响应是针对哪个文件的 回调的执行顺序有保证吗?或者我可以以某种方式向回调提供我没有想到的索引吗?显然,我在这里尝试使用“var k”失败了:/Javascript Multiple path.exists回调,如何知道返回状态是针对哪个文件的?,javascript,node.js,Javascript,Node.js,用于检查文件是否异步存在的node.js内置库函数仅向回调提供布尔值“exists”。我需要检查是否存在多个似乎有问题的文件。我如何知道响应是针对哪个文件的 回调的执行顺序有保证吗?或者我可以以某种方式向回调提供我没有想到的索引吗?显然,我在这里尝试使用“var k”失败了:/ var path = require('path'); var sys = require('sys'); var paths = new Array(); paths.push('file_0'); paths.pu
var path = require('path');
var sys = require('sys');
var paths = new Array();
paths.push('file_0');
paths.push('file_1');
paths.push('file_2');
for (var i = 0; i < paths.length; i++)
{
var k = i;
path.exists(paths[i], function(exists) {
var j = i;
sys.puts("One of the files has this status: " + exists + " but which one?");
sys.puts("j is: "+j);
sys.puts("k is: "+k);
});
}
不幸的是,Javascript将所有变量声明提升到函数顶部,这既愚蠢又不直观。一些解决方法:使用“(function(){my loop code})();”效果很好,谢谢!
$ node test.js
One of the files has this status: false but which one?
j is: 3
k is: 2
One of the files has this status: false but which one?
j is: 3
k is: 2
One of the files has this status: false but which one?
j is: 3
k is: 2