How to implement a pseudo blocking async queue in JS/TS?

后端 未结 2 835
野趣味
野趣味 2020-11-29 12:30

So here\'s an oxymoron: I want to create an asynchronous blocking queue in javascript/typescript (if you can implement it without typescript, that\'s fine). Basically I want

2条回答
  •  清歌不尽
    2020-11-29 13:00

    This is simply @Bergi's answer but with typescript + generics with some modifications to make it work with strict mode for my typing brothers/sisters out there.

    class AsyncBlockingQueue {
      private _promises: Promise[];
      private _resolvers: ((t: T) => void)[];
    
      constructor() {
        this._resolvers = [];
        this._promises = [];
      }
    
      private _add() {
        this._promises.push(new Promise(resolve => {
          this._resolvers.push(resolve);
        }));
      }
    
      enqueue(t: T) {
        if (!this._resolvers.length) this._add();
        const resolve = this._resolvers.shift()!;
        resolve(t);
      }
    
      dequeue() {
        if (!this._promises.length) this._add();
        const promise = this._promises.shift()!;
        return promise;
      }
    
      isEmpty() {
        return !this._promises.length;
      }
    
      isBlocked() {
        return !!this._resolvers.length;
      }
    
      get length() {
        return this._promises.length - this._resolvers.length;
      }
    }
    

提交回复
热议问题