nodejs fs.exists (fs.access) 在 for 循环中发生奇怪的事情

Sha*_*n 蔡 2 for-loop fs node.js

我的代码:

for(var i=0; i<2; i++)
{
    console.log("idx: " + i);

    fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
      console.log(err ? 'no access!'+i : 'can read/write'+i);
    });

    fs.exists('/etc/passwd', (exists) => {
      console.log(exists ? 'it\'s there'+i : 'no passwd!'+i);
    });
}
Run Code Online (Sandbox Code Playgroud)

结果:
idx: 0
idx: 1
无法访问!2
就在那里2
无法访问!2
就在那里2

为什么我=2?
我该如何解决它?

Dav*_*nte 5

你问题的关键是异步。两个 fs 方法都是异步的,稍后会执行,当它们即将执行时,i 的值为 2,因为循环已经完成。

解决这个问题最简单的方法是通过 let 更改循环 var 的声明

for(let i=0; i<2; i++)
Run Code Online (Sandbox Code Playgroud)

它将 i 的范围限制为一次迭代