我想要一个这样的功能:
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