1
function DatabaseConnect(req, res) {...}
function CreateNewUser(req, res) {...}

function Go (app, req, res) {

    // If is POST on this URL run this function
    var firstFunction = app.post('/admin/svc/DB', function(res, req) { 
        DatabaseConnect(req, res) 
    });

    // If is POST on this URL run this function
    var secondFunction = app.post('/admin/svc/CREATE', function(res, req) { 
        CreateNewUser(req, res) 
    });

    // Run first all callbacks and after render page
    function Render(firstMe, afterMe) {
        firstMe();
        afterMe();
        app.render('screen');
    }

    Render(firstFunction, secondFunction);

}

Go();   

我怎样才能运行更多的异步功能。和 Render() 毕竟?

如果在该 URI 上进行了 POST,则调用 APP.POST。

4

1 回答 1

0

根据您的需要,这里有各种不同的方法。如果您只关心完成一定数量的异步函数,一种常见的模式是基本上维护一个计数并afterAll()在完成后触发该方法:

var count = 0,
    target = 2; // the number of async functions you're running

function afterAll() {
    if (++count === target) {
        // do something
    }
}

doAsync1(function() {
    // some stuff
    afterAll();
});

doAsync2(function() {
    // some stuff
    afterAll();
});

Underscore在这里提供了一些有用的实用程序,包括_.after

var asyncMethods = [doAsync1, doAsync2, doAsync3],
    // set up the callback to only run on invocation #3
    complete = _.after(asyncMethods.length, function() {
        // do stuff
    });
// run all the methods
asyncMethods.forEach(function(method) {
    // this assumes each method takes a callback
    method(complete);
});
于 2012-12-22T23:47:30.113 回答