在 for 循环内部调用异步函数 [英] Call asynchronous function inside for loop
本文介绍了在 for 循环内部调用异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
});
}
如何访问传递给 fs.lstat 函数的 path
变量?
How can I access the path
variable, that was passed to fs.lstat function?
推荐答案
这是使用 .forEach()
而不是 for 循环来迭代值.
This is a perfect reason to use .forEach()
instead of a for loop to iterate values.
paths.forEach(function( path ) {
fs.lstat( path, function(err, stat) {
console.log( path, stat );
});
});
此外,您可以使用@Aadit 建议的闭包:
Also, you could use a closure like @Aadit suggests:
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
}
这篇关于在 for 循环内部调用异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文