Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What is the proper way to call 'render' after all async executions in controller?

What is the proper way to call 'render' after all async executions in controller?

Problem

So here we have some application based on 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 render template index after the end of all callbacks?

Maybe there is something like jQuery's $.when described in this answer?

Problem courtesy of: FelikZ

Solution

Conceptually, you just need to keep track of the number of Async calls returning you are waiting for, which I've illustrated in your code below. But there are loads of little libraries that make this a lot more generic, elegant and give you more control (like making sure they run in sequence and similar stuff). async.js for instance.


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

});
Solution courtesy of: Marius Kjeldahl

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

What is the proper way to call 'render' after all async executions in controller?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×