[英]How to use yield in Typescript classes
I am fresher to Typescript, while learning from the site, I got to know that yield can be used for Asynchronous Iteration using for-await-of.我对 Typescript 比较陌生,在从网站学习的过程中,我了解到使用 for-await-of 可以将 yield 用于异步迭代。 The below is the function in Javascript.
下面是Javascript中的function。 Please help me how to use in Typescript classes.
请帮助我如何在 Typescript 类中使用。 When I write the below code, I get the error as TS1163: A 'yield' expression is only allowed in a generator body.
当我编写下面的代码时,我得到的错误是TS1163: A 'yield' expression is allowed in a generator body。 I want to write the below code in Typescript class .
我想在 Typescript class 中编写以下代码。
https://blog.bitsrc.io/keep-your-promises-in-typescript-using-async-await-7bdc57041308 . 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();
I also tried to write in a Typescript class, but it gives compilation issue.我还尝试编写 Typescript class,但它给出了编译问题。
public getValues(): number {
let index = 1;
while(true) {
yield index;
index = index + 1;
if (index > 10) {
break;
}
}
}
You need to put the token *
in from of you method:您需要将令牌
*
放入 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.