for-await-of 简单示例(打字稿)

Pra*_*tta 5 typescript

在 typescript 2.3 中引入了一个新功能 for-await-of 任何人都可以发布一个简单的示例来说明如何将其与 Promise 一起使用以及其主要用例是什么,我正在研究更改日志中的示例

async function f() {
  for await (const x of g()) {
 console.log(x);
 }
}
Run Code Online (Sandbox Code Playgroud)

但对用例不太了解

dan*_*nvk 5

下面是一个使用 for-await-of 打印“1”的示例,等待一秒钟,然后打印“2”:

// Polyfill Symbol.asyncIterator
(Symbol as any).asyncIterator = Symbol.asyncIterator || Symbol("Symbol.asyncIterator");

async function sleep(ms: number): Promise<void> {
  return new Promise<void>((resolve, reject) => {
    setTimeout(resolve, ms);
  });
}

async function* asyncGenerator() {
  yield 1;
  await sleep(1000);
  yield 2;
}

(async() => {
  for await (const num of asyncGenerator()) {
    console.log(num);
  }
})().catch(e => console.error(e));
Run Code Online (Sandbox Code Playgroud)

TypeScript 2.3 发行说明有一些有用的警告

  • 您需要包含esnextcompilerOptions.lib您的设置中tsconfig.json(或--lib命令行标志中)。
  • 您需要compilerOptions.downlevelIterators在您的tsconfig.json(或--downlevelIterators在命令行上)中进行设置。
  • 您可能需要一个Symbol.asyncIteratorpolyfill(包含在上面的代码片段中)。