views:

46

answers:

2

Hi there,

is there any best-practice-pattern for implementing a queue for sending ordered requests? I know this hits the logic behind ansynchronous requests, but in special cases one needs queued sending :)

Here is my first attempt:

this.queue = [],
this.sending = false,  
send: function(message) {
    if (this.sending) {
        this.queue.push(message);
    } else {
        else this.push(message);
    }
},
push: function(message) {
    this.sending = true;
    new Ajax.Request(this.outURL + "&message=" + encodeURIComponent(message), {
        onSuccess: function() {
            this.sending = false;
            if (this.queue.size() > 0) {
                this.push("queued: " + this.queue.shift());
            }
        }.bind(this)
    });
},

Is there any better implementation? Thank you in advance :)

A: 

Please don't let me die alone with it :( I don't get it working right. The code above does not queue messages right. They are sent in different order. Does anybody know a solution? Thank you!

Moo
A: 

Do not die alone!! I think your class/namespace may be a little messed up since your mixing : and = (you cannot use = inside of an object {} namespace )

AjaxQueue = {
    outURL: '/ajax.html',
    queue: [],
    sending: false,

    //Stick message on the queue array
    send: function(message) {
        this.queue.push(message);
        this.iterate();
    },
    //If theres a message on the queue array send it, then recursively calls itself
    iterate: function() {
        message = this.queue.pop()
        //this will be false and stop recursion when there are no more messages
        if (message)
        {
            new Ajax.Request(this.outURL, {
                //no need to use string appending or encodeURL, prototype does this for you
                parameters: {message: message},
                method: 'GET',
                onSuccess: function() {
                    //recursion.  We avoid this because it wont be in scope
                    AjaxQueue.iterate()
                }
            });
        }
    }
}

Code to test

AjaxQueue.send('First Message'); AjaxQueue.send('Second message'); AjaxQueue.send('Third Message')

Try this with a real big file or slow script and you'll see the queue functionality work.

Lincoln B