什么 AsyncGenerator TypeScript 类型产生 Promise?

What AsyncGenerator TypeScript type yields a Promise?

我正在尝试将 return 类型分配给以下函数:

async function *sleepyNumbers() {  // what TypeScript type is this?
  let n = 0;
  while (true) {
    yield new Promise(resolve => resolve(n++));
    await new Promise(resolve => setTimeout(resolve, 500));
  }
}

(async () => {
  for await (const i of sleepyNumbers())
    console.log(i);
})();

生成器正在生成解析为 number 的 Promise。将类型设置为 Promise<number> 失败并显示此错误消息:

TS2739: Type 'AsyncGenerator' is missing the following properties from type 'Promise': then, catch, [Symbol.toStringTag], finally

Iterable 导致了类似的错误。

我可以将类型设置为 AsyncGenerator 但这不够具体。此函数的 return 类型的正确 TypeScript 语法是什么?

它将是 AsyncGenerator<number, never, void>:

number - next 结果
neverreturns
void - next 没有得到任何参数

您还需要明确键入承诺解析:

yield new Promise<number>(resolve => resolve(n++));

总计:

async function *sleepyNumbers(): AsyncGenerator<number, never, void> {
    let n = 0;
    while (true) {
        yield new Promise<number>(resolve => resolve(n++));
        await new Promise(resolve => setTimeout(resolve, 500));
    }
}

(async () => {
    for await (const i of sleepyNumbers())
        console.log(i);
})();

因为看这里的很多人都需要一些退出条件,所以我将问题和 调整为:

  1. 让它在 4 次迭代后停止:
  2. 修复结果 error TS2534: A function returning 'never' cannot have a reachable end point.(使用库“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 要求将 AsyncGenerator 的第二个模板参数设为 void,因为生成器函数(function*)在没有 return 的情况下结束,并且来电者回来:

{ value: undefined, done: true }

调整生成器以在完成时传递最终值,我们看到第二个模板参数的使用:

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());
})();

,生成输出:

{ 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 }

显然,在生成器完成后敲击迭代器总是会返回 value: undefined

tldr;(好像这还不是 tldr 领域),我们一直在玩 AsyncGenerator 模板的 TReturn 参数:

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>;
}

(根据 node_modules/typescript/lib/lib.es2018.asyncgenerator.d.ts),映射到

中的 TReturn
interface IteratorYieldResult<TYield> {
    done?: false;
    value: TYield;
}

interface IteratorReturnResult<TReturn> {
    done: true;
    value: TReturn;
}

type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;

(每个库。es2015.iterable.d.ts)