问题
I'm working on an Express app. At startup it connects to a Redis server and to a PostgreSQL sever. I'd like to wait for both connections to succeed before starting the express server. Now, if I were waiting on just one callback, I could initiate the Express server within that callback. But how to best do this when waiting on more than one async operation? I'm new to this. Is there a good idiomatic pattern for doing this sort of thing? Maybe grouping promises together or..?
回答1:
Promises are what you want.
You can use .all()
on an array of promises to wait for them all to complete. You didn't mention what Promise library you're using, but it's fairly universal. here's the Bluebird documentation: https://github.com/petkaantonov/bluebird/blob/master/API.md#all---promise
回答2:
Promises are probably the idiomatic way to solve this. You will have to "promisify" your functions that return callbacks to turn them into something that returns and resolves promises, but then Promise.all()
will work just fine. I personally use Bluebird for my nodejs development and regularly promisify existing functions or whole modules that use asynchronous callbacks.
If you aren't otherwise using a library that can promisify non-promised functions, then you can also just use a counter to keep track of when all your callbacks are done. This is the "older fashioned" way of doing things, but works just fine too. Such an operation works like this:
function setup(fn) {
// initialize counter to number of async operations
var counter = 3;
function checkDone() {
--counter;
if (counter <= 0) {
fn();
}
}
firstAsyncFunction(...., checkDone);
secondAsyncFunction(...., checkDone);
thirdAsyncFunction(...., checkDone);
}
setup(function() {
// this will get called when all the initial async operations are done
});
来源:https://stackoverflow.com/questions/28122225/wait-for-several-db-connections-before-starting-express-server