CNode

求教,为什么在node中,循环遍历读取文件状态,在内部push进数组可以拿到数据,但是在forEach循环中打印数组为空。

问答
Yyangweixin1406发布于7 年前最后回复7 年前4 回复3656 浏览0 收藏

userful.png

查看回复

回复 (4)

H
hsiaosiyuan0#1·7 年前

因为 console.log 执行到的时候,写在回调里面的 arr.push 还没执行到

Y
yangweixin1406#2·7 年前
引用 hsiaosiyuan0因为 console.log 执行到的时候,写在回调里面的 arr.push 还没执行到

@hsiaosiyuan0 有什么方法可以在外部拿到 arr.push 的数据吗?

H
hsiaosiyuan0#3·7 年前
function readFilesStat(files, cb) {
  const arr = [];
  const x_done = () => files.length === arr.length && cb(arr.filter(s => s !== null));
  files.forEach(file => {
    fs.stat('some-prefix' + file, (err, stat) => {
      if(err) arr.push(null);
      else arr.push({/* custom stat obj */});
      x_done();
    });
  });
}
Y
yangweixin1406#4·7 年前
引用 hsiaosiyuan0

@hsiaosiyuan0 谢谢谢谢

参与回复
登录后即可参与回复。登录