For those seeking an exit condition, I have modified the question and adapted Aleksey L.'s answer as follows:
- terminate after 4 iterations:
- solve the resulting
error TS2534: A function returning 'never' cannot have a reachable end point.
(tested using the lib "es2018.asyncgenerator").
async function* sleepyNumbers(count: number): AsyncGenerator<number, void, void> {
let n = 0;
while (n < count) {
yield new Promise<number>(resolve => resolve(n++));
await new Promise(resolve => setTimeout(resolve, 250));
}
}
(async () => {
for await (const i of sleepyNumbers(4))
console.log(i);
})();
#2 involved changing the 2nd template argument to void
in AsyncGenerator
because the generator function (the function*
) reaches the end without a return statement, causing the caller to receive:
{ value: undefined, done: true }
By adjusting the generator to pass a final value when finished, we utilize the 2nd template parameter:
async function* sleepyNumbers(count: number): AsyncGenerator<number, string, void> {
let n = 0;
while (n < count) {
yield new Promise<number>(resolve => resolve(n++));
await new Promise(resolve => setTimeout(resolve, 250));
}
return 'some string';
}
(async () => {
const it = sleepyNumbers(4);
let res;
for (res = await it.next(); !res.done; res = await it.next())
console.log(res);
console.log('Finished with:', res);
console.log('past end 1:', await it.next());
console.log('past end 2:', await it.next());
})();
, which yields the following output:
{ value: 0, done: false }
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
Finished with: { value: 'some string', done: true }
past end 1: { value: undefined, done: true }
past end 2: { value: undefined, done: true }
It seems that accessing an iterator after the generator has completed will always result in value: undefined
.
tldr; (although this is quite lengthy already), we examined the usage of the TReturn
parameter in the AsyncGenerator template:
interface AsyncGenerator<T = unknown, TReturn = any, TNext = unknown> extends AsyncIterator<T, TReturn, TNext> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...args: [] | [TNext]): Promise<IteratorResult<T, TReturn>>;
return(value: TReturn | PromiseLike<TReturn>): Promise<IteratorResult<T, TReturn>>;
throw(e: any): Promise<IteratorResult<T, TReturn>>;
[Symbol.asyncIterator](): AsyncGenerator<T, TReturn, TNext>;
}
(as per
node_modules/typescript/lib/lib.es2018.asyncgenerator.d.ts
), where it corresponds to
TReturn
in
interface IteratorYieldResult<TYield> {
done?: false;
value: TYield;
}
interface IteratorReturnResult<TReturn> {
done: true;
value: TReturn;
}
type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;
(according to lib.es2015.iterable.d.ts)