What is the correct way to call "render" after all the asynchronous executions in the controller?

So, here we have an application based on the CompoundJS framework and some controller on it:

load('application');

action('index', function () {
    someMethodWithAsyncCallback({}, function () {
        /* async preparing some params for template */
    });

    anotherMethodWithAsyncCallback({}, function () {
        /* async preparing another params for template */
    });

    // another couple of async calls

    // rendering index template
    render('index', { /* using async params */ });
});

      

The question is, how to make the template index

after all callbacks have finished?

Perhaps something like jQuery is $.when

described in this answer ?

+3


source to share


1 answer


It is clear that you just need to keep track of the number of async calls you expect, which I illustrated in your code below. But there are many small libraries out there that make this much more general, elegant, and give you more control (for example, make sure they work in consistency and stuff like that). async.js , for example.




load('application');

action('index', function () {

    var asyncCounter = 2; // Or whatever number of async you want to complete...
    var completeFunc = function() {
        if (--asyncCounter > 0) {
            return;
        }
        // rendering index template
        render('index', { /* using async params */ });
    };

    someMethodWithAsyncCallback({}, function () {
        /* async preparing some params for template */
        completeFunc();
    });

    anotherMethodWithAsyncCallback({}, function () {
        /* async preparing another params for template */
        completeFunc();
    });

    // another couple of async calls

});

      

+2


source







All Articles