在控制器中执行所有异步执行后调用'render'的正确方法是什么?

时间:2013-01-27 13:23:23

标签: javascript node.js asynchronous callback compoundjs

所以这里我们有一些基于CompoundJS框架的应用程序和一些控制器:

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 */ });
});

问题是:如何在所有回调结束后呈现模板index

也许在this answer中描述了jQuery的$.when

1 个答案:

答案 0 :(得分:2)

从概念上讲,您只需跟踪正在等待的异步调用返回的数量,我已在下面的代码中说明了这一点。但是有很多小库使这个更通用,更优雅并且给你更多的控制(比如确保它们按顺序运行和类似的东西)。例如async.js


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

});