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。
最佳答案
这里有各种不同的方法,具体取决于您的需求。如果您只关心完成一定数量的异步函数,一种常见的模式是基本上维护一个计数并在完成时触发 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);
});
关于javascript - Express/NodeJs 中更好的回调 Javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14007273/