调用内部的异步函数进行循环

时间:2022-08-26 11:15:05
var path;

for (var i = 0, c = paths.length; i < c; i++)
{
    path = paths[i];

    fs.lstat(path, function (error, stat)
    {
        console.log(path); // this outputs always the last element
    });
}

How can I access the path variable, that was passed to fs.lstat function?

如何访问传递给fs的path变量。lstat函数?

3 个解决方案

#1


27  

This is a perfect reason to use .forEach() instead of a for loop to iterate values.

这是使用. foreach()而不是for循环迭代值的完美理由。

paths.forEach(function( path ) {
  fs.lstat( path, function(err, stat) {
    console.log( path, stat );
  });
});

Also, you could use a closure like @Aadit suggests:

此外,您还可以使用@Aadit建议的闭包:

for (var i = 0, c = paths.length; i < c; i++)
{
  // creating an Immiedately Invoked Function Expression
  (function( path ) {
    fs.lstat(path, function (error, stat) {
      console.log(path, stat);
    });
  })( paths[i] );
  // passing paths[i] in as "path" in the closure
}

#2


11  

Classic problem. Put the contents of the for loop in another function and call it in the loop. Pass the path as a parameter.

经典的问题。将for循环的内容放在另一个函数中,并在循环中调用它。将路径作为参数传递。

#3


1  

Recursion works nicely here (especially if you have some i/o that must be executed in a synchronous manner):

递归在这里工作得很好(特别是如果您有一些必须以同步方式执行的i/o):

(function outputFileStat(i) {
    var path = paths[i];

    fs.lstat(path, function(err, stat) {
         console.log(path, stat);
         i++;
         if(i < paths.length) outputFileStat(i);
    });
})(0)

#1


27  

This is a perfect reason to use .forEach() instead of a for loop to iterate values.

这是使用. foreach()而不是for循环迭代值的完美理由。

paths.forEach(function( path ) {
  fs.lstat( path, function(err, stat) {
    console.log( path, stat );
  });
});

Also, you could use a closure like @Aadit suggests:

此外,您还可以使用@Aadit建议的闭包:

for (var i = 0, c = paths.length; i < c; i++)
{
  // creating an Immiedately Invoked Function Expression
  (function( path ) {
    fs.lstat(path, function (error, stat) {
      console.log(path, stat);
    });
  })( paths[i] );
  // passing paths[i] in as "path" in the closure
}

#2


11  

Classic problem. Put the contents of the for loop in another function and call it in the loop. Pass the path as a parameter.

经典的问题。将for循环的内容放在另一个函数中,并在循环中调用它。将路径作为参数传递。

#3


1  

Recursion works nicely here (especially if you have some i/o that must be executed in a synchronous manner):

递归在这里工作得很好(特别是如果您有一些必须以同步方式执行的i/o):

(function outputFileStat(i) {
    var path = paths[i];

    fs.lstat(path, function(err, stat) {
         console.log(path, stat);
         i++;
         if(i < paths.length) outputFileStat(i);
    });
})(0)