tomasbedrich
tomasbedrich

Reputation: 1370

Blocking queue in Javascript

I need to create a blocking queue in Javascript. There are pop() and shift() methods in Array.prototype, but the description says:

Return value: The last element from the array; undefined if the array is empty.

I need a method which does not return undefined, but waits until there is some element to return.

The purpose is, that my code is driven by multiple asynchronous operations which pushes elements to the queue and I need to process them.

Upvotes: 1

Views: 3380

Answers (1)

Maxx
Maxx

Reputation: 1748

Simple implementation with push shift

function Queue() {
  this.listeners = [];
  this.queue = [];
}

Queue.prototype = {
  shift: function(cb) {
    this.queue.length > 0 ? cb(this.queue.shift()) : this.listeners.push(cb);
  },
  push: function(value) {
    if (this.listeners.length > 0) {
      this.listeners.shift()(value);
      return;
    }

    this.queue.push(value);
  }
}


var queue = new Queue();

// 'some value'
queue.shift(function(value) { console.log(value); });

setTimeout(function() { 
  queue.push('some value'); 
  queue.push('another value');

  // 'another value'
  queue.shift(function(value){ console.log(value); });
}, 3000);

Upvotes: 3

Related Questions