在 typescript 2.3 中引入了一个新功能 for-await-of 任何人都可以发布一个简单的示例来说明如何将其与 Promise 一起使用以及其主要用例是什么,我正在研究更改日志中的示例
async function f() {
for await (const x of g()) {
console.log(x);
}
}
但对用例不太了解
这是一个使用 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));
TypeScript 2.3 发行说明有一些有用的警告 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-3.html#the-for-await-of-statement
- 您需要包括
esnext
in the compilerOptions.lib
你的设置tsconfig.json
(或在--lib
命令行标志)。
- 你需要设置
compilerOptions.downlevelIterators
在你的tsconfig.json
(or --downlevelIterators
在命令行上)。
- 您可能需要一个
Symbol.asyncIterator
polyfill(包含在上面的代码片段中)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)