title: what would be a better approach to only initialize a service once all databases are succesfully connected
body: <p>I am having a problem where a service needs to connect to three databases using MySQL pools, I only want to start the service once all the databases are successfully connected, I came up with an approach that works, but I'm quite sure that it could be done better as the current one I feel is a bit over complicated, so any input, or a pointer to a design pattern would be greatly appreciated.</p>
  <p>here is the code in my database class:</p>
  <pre><code>module.exports = class DB {
  // this is making the constructor async as I couldn't think of another way
  // because we don't want to start the service until we make sure that we're connected to the 
  // database, the constructor then resolves to an instance of the class, so when initilizing a class
  // we need to await to get back the instance.
  constructor() {
      return (async () =&gt; {
          this.retries = 0;
          await this.initialize();
          return this;
      })();
  
  }
  
  async initialize() {
      logger.info(&quot;initialzing database connections&quot;);
  
      this.db = mysql.createPool(config.get('db'));
      this.db.asyncQuery = util.promisify(this.db.query);
  
      this.statisticsDb = mysql.createPool(config.get('statisticsDb'));
  
      this.provisioningDb = mysql.createPool(config.get('provisioningDb'));
  
  
      const success = await this.testConnections();
  
      // retry up to 4 times, if all of them fail we will shutdown the process.
      while (this.retries &lt;= 4) {
          if (success) break;
  
          if (this.retries &gt; 3) {
              Logger.error(`Error connecting to one of the databases pools, number of retries is ${this.retries}, will exit`);
              process.exit(1);
          }
          logger.error(`Error connecting to one of the databases pools, number of retries is ${this.retries}, will retry in 2 seconds`)
          this.retries++;
          // this basically pauses excution for 2 seconds.
          await new Promise(resolve =&gt; setTimeout(resolve, 2000));
          await this.initialize();
      }
  }
  
  
  
  /**
   * Tries to get a connection from each pool, if one of the connections fail, it resolves to false
   * otherwise it resolves to true
   */
  async testConnections() {
  
      const isMainConnected = await this.testDatabasePoolConnection(this.db, 'main');
      const isStatisticsConnected = await this.testDatabasePoolConnection(this.statisticsDb, 'statistics');
      const isprovisioningConnected = await this.testDatabasePoolConnection(this.provisioningDb, 'provisioning');
  
      if (isMainConnected.connected &amp;&amp; isStatisticsConnected.connected &amp;&amp; isprovisioningConnected.connected) {
          this.retries = 0;
          logger.info('All databases successfully connected.')
          return true;
      }
  
      return false;
  }
  
      /**
   * Given a mysql pool, tests if the pool is connected successfully.
   * @param {mysql.Pool} dbPoolInstance the mysql pool we want to test
   * @param {string} dbName the name of the pool for logging purposes
   * @returns resolves to an object, either with error property if there was an error or a connected property if pool is working.
   */
  async testDatabasePoolConnection(dbPoolInstance, dbName) {
      try {
          dbPoolInstance.asyncQuery = util.promisify(dbPoolInstance.query);
          let testQuery = 'SELECT id FROM test LIMIT 1';
          await dbPoolInstance.asyncQuery(testQuery);
          logger.info(`${dbName} database successfully connected`);
          return { connected: true }
      } catch (e) {
          logger.error(`${dbName} database connection failed, Error: ${e}`);
          return { error: e };
      }
  }
  </code></pre>
  <p>and here is the index.js file (simplified):</p>
  <pre><code>initalize();
  
  
  async function initalize() {
      try {
          const db = await new DB()
  
          await cleanUpSomeData(db);
  
          new Server(db);
  
  } catch (e) {
      Logger.error(`Error while trying to intialize the service ${JSON.stringify(e)}, will shutdown the service`);
      process.exit(1);
  }
  </code></pre>
  <p>}</p>