[英]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.