title: How to retry database connection in Node.js when first connect is failed?
body: <p>I am using SQL Server with Node.js. When the connection fails in first attempt the Node.js does not reattempt to connect. I am using <code>setTimeout()</code> to keep trying periodically until it connects.</p>
  
  <pre><code>const poolPromise = new sql.ConnectionPool(config.db);
  poolPromise
    .connect()
    .then(pool =&gt; {
      console.log('Connected to MSSQL');
      return pool;
    })
    .catch(err =&gt; {
      if (err &amp;&amp; err.message.match(/Failed to connect to /)) {
        console.log(new Date(), String(err));
  
        // Wait for a bit, then try to connect again
        setTimeout(function() {
          console.log('Retrying first connect...');
          poolPromise.connect().catch(() =&gt; {});
        }, 5000);
      } else {
        console.error(new Date(), String(err.message));
      }
    });
  </code></pre>
  
  <p>The above code attempt to connect, fails and try for second time but does not continue for third, fourth and so on.</p>