Wait for several db connections before starting express server? Wait for several db connections before starting express server? express express

Wait for several db connections before starting express server?


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


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