title: Using Async/Await with node-postgres
body: <p>I am using node-postgres to query my database and would like to know how to use async/await and handle errors correctly</p>
  
  <p>An example of my use is here with a very simple query</p>
  
  <pre><code>const { Pool } = require('pg');
  
  let config;
  if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
    config = { connectionString: process.env.DATABASE_URL, ssl: true };
  } else {
    config = {
      host: 'localhost',
      user: 'myuser',
      database: 'mydatabase',
    };
  }
  
  const pool = new Pool(config);
  
  async function getAllUsers() {
    let response;
    try {
      response = await pool.query('select * FROM users');
    } catch (error) {
      throw error;
    }
    return response.rows;
  }
  </code></pre>
  
  <p>Then in my <code>routes.js</code> I have</p>
  
  <pre><code>app.get('/all_users', async (req, res) =&gt; {
    const users = await queries.getAllUsers();
    console.log(users); // returns all users fine
  });
  </code></pre>
  
  <p>This is my understanding so far, but i don't think I am approaching this correctly as when it comes to errors my app will freeze and throw <code>UnhandledPromiseRejectionWarning</code>. So if I provide an incorrect table for example</p>
  
  <pre><code>async function getAllUsers() {
    let response;
    try {
      response = await pool.query('select * FROM notable');
    } catch (error) {
      throw error;
    }
    return response.rows;
  }
  
  UnhandledPromiseRejectionWarning: error: relation "notable" does not exist
  </code></pre>
  
  <p>The app will crash after 30 seconds and I have not handled this error gracefully</p>
  
  <p>Could anyone point out what i am missing here please?</p>