1

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.

11
  • how's that different from an event stream? Commented Sep 28, 2016 at 12:12
  • @YuriBlanc why do you want to do complex stuff? Commented Sep 28, 2016 at 12:12
  • 4
    Javascript is single-threaded so this type of pattern doesn't make sense. If the thread is blocked then nothing else runs. Commented Sep 28, 2016 at 12:20
  • 1
    @ccarton a "blocking queue" isn't necessarily the same as "a queue blocking the event loop". Commented Sep 28, 2016 at 12:43
  • 1
    @tomasbedrich take a look at async.queue(). Commented Sep 28, 2016 at 12:44

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

So basically this is a buffer, right? You keep track of "pre-requested" items in this.listeners and "pushed, not requested yet" items in this.queue.
something like that. i guess there are many libraries that do things like this better than my code, try to find something. This code is just for example
This should really use push() and shift() so that it acts like a queue as its name implies rather than a stack. The listeners as well.
I think the terms push and shift should be add and poll respectively

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.