Javascript 创建一个迭代器来充当一个可观察/执行通道,为什么它只发出未分组的异步事件?

Javascript 创建一个迭代器来充当一个可观察/执行通道,为什么它只发出未分组的异步事件?,javascript,typescript,ecmascript-6,Javascript,Typescript,Ecmascript 6,我正在为rxjs和Golang通道的反应性处理器建模。我试图使用迭代器来实现这一点,但是我的“通道”仅在提供异步事件时发出。为什么呢 这是我的消费代码 import { Channel } from "./channel"; const numbers: any = new Channel(); void async function() { for (const number of numbers) { // Will pause and wait for emit()

我正在为rxjs和Golang通道的反应性处理器建模。我试图使用迭代器来实现这一点,但是我的“通道”仅在提供异步事件时发出。为什么呢

这是我的消费代码

import { Channel } from "./channel";

const numbers: any = new Channel();

void async function() {
  for (const number of numbers) {
    // Will pause and wait for emit()
    console.log(await number);
  }
}();

numbers.emit(1);
numbers.emit(2);
numbers.emit(3);
setTimeout(() => numbers.emit(4));
setTimeout(() => numbers.emit(5), 50);
setTimeout(() => numbers.emit(6), 100);
这是我的“通道”实现

export class Channel<T = any> {
  private onValue = new PromiseSubject()

  emit(value: T): void {
    this.onValue.resolve(value)
    this.onValue = new PromiseSubject()
  }

  *[Symbol.iterator](): Iterator<Promise<T>> {
    while (true) {
      yield this.onValue.promise
    }
  }    
}

export class PromiseSubject<T = any> {
  public resolve!: (value?: T) => void
  public promise = new Promise<T>((res) => this.resolve = res)
}
沙盒链接:
因为您需要实现某种队列。 与

您重写当前的
onValue
,当您调用迭代器(使用
for of
)时,您只等待当前的
onValue
,而不是之前存储在那里的承诺

不过,也有异步迭代器,它们完全满足您的要求

 export class Channel<T = any> {
   toEmit = [] as T[];
   resolveLast: Promise?;

  emit(value: T): void {
    if(this.resolveLast) this.resolveLast(value);
    else this.toEmit.push(value);
  }

  async *[Symbol.iterator](): {
    while (true) {
      const value = this.toEmit.shift();
      yield value;
      if(this.toEmit.length === 0)
         await new Promise(res => this.resolveLthis.resolveLast = res);
    }
  }    
}

 // iterable as
 for await(const el of new Channel)
导出类频道{
toEmit=[]作为T[];
最后:承诺?;
发射(值:T):无效{
if(this.resolveLast)this.resolveLast(value);
否则这个.toEmit.push(值);
}
异步*[Symbol.iterator]():{
while(true){
常量值=this.toEmit.shift();
收益值;
if(this.toEmit.length==0)
等待新的承诺(res=>this.resolveLthis.resolvellast=res);
}
}    
}
//可作为
等待(新通道的常数)
建议阅读:

 this.onValue = new PromiseSubject()
 export class Channel<T = any> {
   toEmit = [] as T[];
   resolveLast: Promise?;

  emit(value: T): void {
    if(this.resolveLast) this.resolveLast(value);
    else this.toEmit.push(value);
  }

  async *[Symbol.iterator](): {
    while (true) {
      const value = this.toEmit.shift();
      yield value;
      if(this.toEmit.length === 0)
         await new Promise(res => this.resolveLthis.resolveLast = res);
    }
  }    
}

 // iterable as
 for await(const el of new Channel)