2

I am attempting to implement an asynchronous method queue in Javascript as seen in this blog post

Here's what I have so far:

function Queue() {
  this._methods = [];
  this._response = null;
  this._flushed = false;
}

(function(Q){

  Q.add = function (fn) {
    if (this._flushed) fn(this._response);
    else this._methods.push(fn);
  }

  Q.flush = function (response) {
    if (this._flushed) return;
    this._response = response;
    while (this._methods[0]) {
      this._methods.shift()(response);
    }
    this._flushed = true;
  }

})(Queue.prototype);

I can't seem to get it to work as advertised, although the code looks correct to me. When I call the flush function I get this._methods is undefined on the line while (this._methods[0]) {.

1 Answer 1

2

How are you using it? If you're doing:

var q = new Queue();
q.flush("foo");

...you shouldn't be getting that error, and I'm not: http://jsbin.com/iduji3

Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, I'm using it as a constructor. That's what's so weird.
Okay, looks like there was a scoping problem with the way I was using Queue#flush as a callback. It is working okay.
@Adam: Ah, if you were using it as a callback, your problem would be that this won't be what you're expecting in the callback. Two blog posts on this: You must remember this and Mythical Methods The second one is probably more on-target for what you're trying to do.
J. Yeah, I was inadvertently passing the function into a different scope. Dumb mistake. Moral: probably shouldn't have been coding at 3am. Calling queue.flush from within an anonymous function works fine.

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.