我有一个异步生成器:
async function* foo() {
yield "wait...";
await new Promise(r=>setTimeout(r, 900));
yield new Promise(r=>setTimeout(()=>r("okay!"), 100));
}
async function main() {
for await (let item of foo()) {
let result = await item;
console.log(result);
}
}
main();
Run Code Online (Sandbox Code Playgroud)
但是使用typescript 2.3,这给了我错误:
错误TS2318:找不到全局类型'AsyncIterableIterator'.example.ts(10,26):
错误TS2504:类型必须具有返回异步迭代器的'Symbol.asyncIterator'方法.
如何修复此错误以及如何运行异步生成器?
假设我有一个函数接受生成器并返回第一个n元素的另一个生成器:
const take = function * (n, xs) {
console.assert(n >= 0);
let i = 0;
for (const x of xs) {
if (i == n) {
break;
}
yield x;
i++;
}
};
Run Code Online (Sandbox Code Playgroud)
用法如下:
const evens = function * () {
let i = 0;
while (true) {
yield i;
i += 2;
}
};
for (const x of take(10, evens())) {
console.log(x);
}
Run Code Online (Sandbox Code Playgroud)
现在想象一下,evens也是async(见这个答案的设置):
const evensAsync = async function * …Run Code Online (Sandbox Code Playgroud)