微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – TypeScript:异步生成器

我想要这样的功能
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 (const line of readLines(filePath)) {
  console.log(line);
}

哪里

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

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

原文地址:https://www.jb51.cc/js/153365.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐