- Learning TypeScript 2.x
- Remo H. Jansen
- 235字
- 2025-04-04 17:02:05
Asynchronous generators
We have already learned about the interface that is implemented by all iterators:
interface Iterator<T> { next(value?: any): IteratorResult<T>; return?(value?: any): IteratorResult<T>; throw?(e?: any): IteratorResult<T>; }
However, we haven't yet learned about the interface that is implemented by all asynchronous iterators:
interface AsyncIterator<T> { next(value?: any): Promise<IteratorResult<T>>; return?(value?: any): Promise<IteratorResult<T>>; throw?(e?: any): Promise<IteratorResult<T>>; }
An asynchronous iterator returns a promise every time we invoke the next method. The following code snippet demonstrates how asynchronous iterators can be very useful when used in conjunction with asynchronous functions:
let counter = 0; function doSomethingAsync() { return new Promise<number>((r) => { setTimeout(() => { counter += 1; r(counter); }, 1000); }); } async function* g1() { yield await doSomethingAsync(); yield await doSomethingAsync(); yield await doSomethingAsync(); } let i = g1(); i.next().then((n) => console.log(n)); // 1 i.next().then((n) => console.log(n)); // 2 i.next().then((n) => console.log(n)); // 3
Some additional types are required by asynchronous iterators if we are targeting ES5. You will need to add esnext.asynciterable to your tsconfig.json file. We are also going to need to enable an additional setting in our tsconfig.json to provide full support for iterables (for example, using for...of control flow statements, the spread operator or object destructuring) when targeting ES3 or ES5:
"lib": [
"es2015.promise",
"dom",
"es5",
"es2015.generator",
"es2015.iterable",
"esnext.asynciterable" // new
]
We will learn more about the lib setting in Chapter 9, Automating Your Development Workflow .
"lib": [
"es2015.promise",
"dom",
"es5",
"es2015.generator",
"es2015.iterable",
"esnext.asynciterable" // new
]
We will learn more about the lib setting in Chapter 9, Automating Your Development Workflow .