请教一个 js 问题,实现类似 go channel 的功能

2020-02-15 00:35:10 +08:00
 xcstream
class JSChannel{
constructor(){
//todo
}

output(){
//todo

}

input(item){
//todo
}
}



var chan = new JSChannel()
chan.input(1)
chan.input(2)
chan.input(3)

async function runloop(){
while(1){
var v = await chan.output()
console.log(v)
}
}
runloop()

setInterval(
function(){
chan.input(new Date())
},1000
)

//一端输入一端输入,没有输入时候停住,知道有输入时返回
//输出 1 2 3 然后一秒出一次时间
2420 次点击
所在节点    JavaScript
7 条回复
ericls
2020-02-15 01:23:07 +08:00
包个 promise 就行啦
godoway
2020-02-15 02:07:12 +08:00
听说过 rxjs 吗
var subject = new Subject()
subject.subscribe(msg => console.log(msg))

subject.next(1)
subject.next(2)
subject.next(3)
jinliming2
2020-02-15 02:40:23 +08:00
用 async generator 比较合适?
noe132
2020-02-15 02:47:58 +08:00
你听说过 eventemitter 吗
xcstream
2020-02-17 01:48:53 +08:00
我知道你们说的东西,但是 只在这 3 个地方填代码是否可以实现。
chnwillliu
2020-03-11 09:36:51 +08:00
```
class JSChannel {
constructor() {
this.outputBuffer = [];
this.inputBuffer = [];
}

output() {

if(this.inputBuffer.length) {
const input = this.inputBuffer.shift();
return Promise.resolve(input);
}

const defferred = (() => {
let resolve, reject;
let promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});

return {
promise,
resolve,
reject
};
})();

this.outputBuffer.push(defferred);
return defferred.promise;
}

input(item) {
if(this.outputBuffer.length) {
const output = this.outputBuffer.shift();
output.resolve(item);
return;
}

this.inputBuffer.push(item);
}
}
```
xcstream
2020-03-11 11:20:54 +08:00
@chnwillliu 试了一下可以的!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/644680

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX