简体   繁体   English

在for循环中调用异步函数

[英]Call asynchronous function inside for loop

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.lstat函数的path变量?

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
}

Classic problem. 经典问题。 Put the contents of the for loop in another function and call it in the loop. 将for循环的内容放在另一个函数中并在循环中调用它。 Pass the path as a parameter. 将路径作为参数传递。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM