javascript 在 for 循环内部调用异步函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7696747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:59:28  来源:igfitidea点击:

Call asynchronous function inside for loop

javascriptnode.jsasynchronousfor-loopscope

提问by Ragnis

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 pathvariable, that was passed to fs.lstat function?

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

回答by gnarf

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
}

回答by Aadit M Shah

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 循环的内容放在另一个函数中并在循环中调用它。将路径作为参数传递。

回答by Mark Gia Bao Nguyen

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)