3

所以这里我们有一些基于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在所有回调结束后渲染模板?

也许这个答案$.when中有类似jQuery的描述?

4

1 回答 1

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

});
于 2013-01-27T14:06:55.387 回答