title: when to disconnect and when to end a pg client or pool
body: <p>My stack is node, express and the pg module. I really try to understand by the documentation and some outdated tutorials. <strong>I dont know when and how to disconnect and to end a client.</strong></p>
  
  <p>For some routes I decided to use a pool. This is my code</p>
  
  <pre><code>const pool = new pg.Pool({
    user: 'pooluser',host: 'localhost',database: 'mydb',password: 'pooluser',port: 5432});
  
  pool.on('error', (err, client) =&gt; {
    console.log('error ', err);  process.exit(-1);
  });
  
  app.get('/', (req, res)=&gt;{
    pool.connect()
      .then(client =&gt; {
        return client.query('select ....')
              .then(resolved =&gt; {
                client.release();
                console.log(resolved.rows);
              })
              .catch(e =&gt; { 
                client.release();
                console.log('error', e);
              })
        pool.end();
      })
  });
  </code></pre>
  
  <p>In the routes of the CMS, I use client instead of pool that has different db privileges than the pool.</p>
  
  <pre><code>const client = new pg.Client({
    user: 'clientuser',host: 'localhost',database: 'mydb',password: 'clientuser',port: 5432});    
  client.connect();
  
  const signup = (user) =&gt; {
    return new Promise((resolved, rejeted)=&gt;{
      getUser(user.email)
      .then(getUserRes =&gt; {
        if (!getUserRes) {
          return resolved(false);
        }            
              client.query('insert into user(username, password) values ($1,$2)',[user.username,user.password])
                .then(queryRes =&gt; {
                  client.end();
                  resolved(true);
                })
                .catch(queryError =&gt; {
                  client.end();
                  rejeted('username already used');
                });
      })
      .catch(getUserError =&gt; {
        return rejeted('error');
      });
    }) 
  };
  
  const getUser = (username) =&gt; {
    return new Promise((resolved, rejeted)=&gt;{
      client.query('select username from user WHERE username= $1',[username])
        .then(res =&gt; {
          client.end();
          if (res.rows.length == 0) {
            return resolved(true);
          }
          resolved(false);
        })
        .catch(e =&gt; {
          client.end();
          console.error('error ', e);
        });
    })
  }
  </code></pre>
  
  <p>In this case if I get a <code>username already used</code> and try to re-post with another username, the query of the <code>getUser</code> never starts and the page hangs. If I remove the <code>client.end();</code> from both functions, it will work. </p>
  
  <p>I am confused, so please advice on how and when to disconnect and to completely end a pool or a client. Any hint or explanation or tutorial will be appreciated. </p>
  
  <p>Thank you</p>