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

So here is 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 to implement something like Java to BlockingQueueexpect instead of actually blocking it, it would be async, and I can wait for the separation.

Here is the interface I want to implement:

interface AsyncBlockingQueue<T> {
  enqueue(t: T): void;
  dequeue(): Promise<T>;
}

And I would use it like this:

// enqueue stuff somewhere else

async function useBlockingQueue() {
  // as soon as something is enqueued, the promise will be resolved:
  const value = await asyncBlockingQueue.dequeue();
  // this will cause it to await for a second value
  const secondValue = await asyncBlockingQueue.dequeue();
}

Any ideas?

+4
source share
2 answers

, dequeue , enqueue . , , , promises .

class AsyncBlockingQueue {
  constructor() {
    // invariant: at least one of the arrays is empty
    this.resolvers = [];
    this.promises = [];
  }
  _add() {
    this.promises.push(new Promise(resolve => {
      this.resolvers.push(resolve);
    });
  }
  enqueue(t) {
    // if (this.resolvers.length) this.resolvers.shift()(t);
    // else this.promises.push(Promise.resolve(t));
    if (!this.resolvers.length) this._add();
    this.resolvers.shift()(t);
  }
  dequeue() {
    if (!this.promises.length) this._add();
    return this.promises.shift();
  }
  // now some utilities:
  isEmpty() { // there are no values available
    return !this.promises.length; // this.length == 0
  }
  isBlocked() { // it waiting for values
    return !!this.resolvers.length; // this.length < 0
  }
  get length() {
    return this.promises.length - this.resolvers.length;
  }
}

TypeScript, , -, .

Queue , . . , promises resolvers.

+6

@Bergi, typescript + generics , /.

class AsyncBlockingQueue<T> {
  private _promises: Promise<T>[];
  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();
    if (!resolve) {
      // can never happen
      throw new Error('resolve function was null or undefined when attempting to enqueue.')
    };
    resolve(t);
  }

  dequeue() {
    if (!this._promises.length) this._add();
    const promise = this._promises.shift();
    if (!promise) {
      // can never happen
      throw new Error('promise was null or undefined when attempting to dequeue.');
    }
    return promise;
  }

  isEmpty() {
    return !this._promises.length;
  }

  isBlocked() {
    return !!this._resolvers.length;
  }

  get length() {
    return this._promises.length - this._resolvers.length;
  }
}
+2

Source: https://habr.com/ru/post/1688874/


All Articles