[英]How to use yield in Typescript classes
我对 Typescript 比较陌生,在从网站学习的过程中,我了解到使用 for-await-of 可以将 yield 用于异步迭代。 下面是Javascript中的function。 请帮助我如何在 Typescript 类中使用。 当我编写下面的代码时,我得到的错误是TS1163: A 'yield' expression is allowed in a generator body。 我想在 Typescript class 中编写以下代码。
https://blog.bitsrc.io/keep-your-promises-in-typescript-using-async-await-7bdc57041308 。
function* numbers() {
let index = 1;
while(true) {
yield index;
index = index + 1;
if (index > 10) {
break;
}
}
}
function gilad() {
for (const num of numbers()) {
console.log(num);
}
}
gilad();
我还尝试编写 Typescript class,但它给出了编译问题。
public getValues(): number {
let index = 1;
while(true) {
yield index;
index = index + 1;
if (index > 10) {
break;
}
}
}
您需要将令牌*
放入 from of you 方法中:
class X {
public *getValues() { // you can put the return type Generator<number>, but it is ot necessary as ts will infer
let index = 1;
while(true) {
yield index;
index = index + 1;
if (index > 10) {
break;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.