使用bluebird

时间:2015-09-13 05:52:03

标签: node.js recursion typescript promise bluebird

我正在尝试使用Node和Bluebird(promises库)以递归方式迭代给定目录,但只要看起来它无法正常工作。

当我取消注释下面的'console.log'行时,它似乎就好像我得到了正确的结果但是我不确定是怎么回事,因为我得到的最终结果是下面的消费代码只是第一个目录中的第一个文件。

也许这个问题不在迭代函数本身,而在于我正在使用它。

我对承诺有点新意,所以也许我只是以错误的方式接近它。

这是我写的代码。

import * as Path from "path";
import * as Promise from "bluebird";
const FS: any = Promise.promisifyAll<any>((require("fs")));
export class Dir {
  public static iterate(path: string) {
    return new Promise((resolve, reject) => {
      FS.lstatAsync(path).then(stat => {
        if (stat.isDirectory()) {
          FS.readdirAsync(path).each(name => {
            let fullPath = Path.join(path, name);
            // console.log(fullPath);
            FS.lstatAsync(fullPath).then(stat => stat.isDirectory() ? Dir.iterate(fullPath) : resolve(fullPath));
          });
        } else {
          reject(`The path '${path}' is not a directory.`)
        }
      });
    })
  }
}

以下是我使用/消费它的方式

Dir.iterate(ProjectPaths.client)
.then(f => {
    console.log(f)
    return f;
})
.catch(e => console.log(e));

编辑:只是为了澄清我正在使用TypeScript!忘了在我的帖子中提到它。

0 个答案:

没有答案