我想要一个这样的功能:

export async function* iterateDir(dir: string) {
    let list = await fs.readdir(dir); // fs-promise implementation of readdir
    for (let file of list) {
        yield file;
    }
}

我会这样使用:
for (let file in iterateDir(dir)) {
    processFile(file);
}

这不起作用,因为函数不能同时是异步的和生成器。

我将如何构造代码以实现相同的目的?
  • 如果我将await fs.readdir更改为回调,则假定外部for..of循环不会等待。
  • 如果我摆脱了生成器,并且目录很大,则iterateDir()会很慢。

  • 供引用:async generator function proposal

    最佳答案

    TypeScript 2.3支持此功能-tracked issue

    它引入了一些新类型,特别是:

    interface AsyncIterable<T> {
        [Symbol.asyncIterator](): AsyncIterator<T>;
    }
    

    但最重要的是,它还引入了for await ... of
    for await (const line of readLines(filePath)) {
      console.log(line);
    }
    

    哪里
    async function* readLines(path) {
       //await and yield ...
    }
    

    请注意,如果您想尝试此操作,则需要配置 typescript 以使其具有运行时支持(将“esnext.asynciterable”添加到lib列表中),您可能需要polyfill Symbol.asyncIterator。见TS2318: Cannot find global type 'AsyncIterableIterator' - async generator

    07-24 09:44
    查看更多