A
A
Alexander Baumgertner2012-02-08 21:24:22
JavaScript
Alexander Baumgertner, 2012-02-08 21:24:22

Correct spelling of an asynchronous application?

Task:
Register the execution of all requests united by a common goal. Execute code when all requests complete.
I have little experience in solving such problems, colleagues, tell me, am I going the right way?
ajax_request and another_ajax_request can be called in arbitrary parts of the code, callback tower blocks are strongly discouraged.
My code:
jsfiddle.net/alexbaumgertner/72dcK

ApplicationDeferreds = {

    deferreds: [],

    done: function(callback) {
        jQuery.when.apply(null, this.deferreds).done(callback);
    },
    register: function(deferred) {
        var self = this;

        // delete resolved
        jQuery.each(this.deferreds, function(index, value) {
            if (value.state() == 'resolved') {
                self.deferreds.splice(self.deferreds.indexOf(value), 1);
            }
        });

        this.deferreds.push(deferred);
    }
};

function ajax_request() {
    ApplicationDeferreds.register(jQuery.get('/'));
}
function another_ajax_request() {
    ApplicationDeferreds.register(jQuery.get('/'));
}

ajax_request();
another_ajax_request();

ApplicationDeferreds.done(function() {
    // do someone
    $('#result').html('done!');
});

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
deadkrolik, 2012-02-09
@deadkrolik

Maybe this api.jquery.com/category/callbacks-object/ will help.

A
Anatoly, 2012-02-08
@taliban

I would do this:
ajax_request(callback1);
ajax_request(callback2);
While this is very dependent on tasks, there are some that require consistency.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question