V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
xcstream
V2EX  ›  JavaScript

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

  •  
  •   xcstream · 2020-02-15 00:35:10 +08:00 · 2388 次点击
    这是一个创建于 1504 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 然后一秒出一次时间
    7 条回复    2020-03-11 11:20:54 +08:00
    ericls
        1
    ericls  
       2020-02-15 01:23:07 +08:00 via iPhone
    包个 promise 就行啦
    godoway
        2
    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
        3
    jinliming2  
       2020-02-15 02:40:23 +08:00 via iPhone
    用 async generator 比较合适?
    noe132
        4
    noe132  
       2020-02-15 02:47:58 +08:00 via Android
    你听说过 eventemitter 吗
    xcstream
        5
    xcstream  
    OP
       2020-02-17 01:48:53 +08:00
    我知道你们说的东西,但是 只在这 3 个地方填代码是否可以实现。
    chnwillliu
        6
    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
        7
    xcstream  
    OP
       2020-03-11 11:20:54 +08:00
    @chnwillliu 试了一下可以的!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5642 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 06:07 · PVG 14:07 · LAX 23:07 · JFK 02:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.