Async Functions with Try-Catch Error Handling

suggest change

One of the best features of async/await syntax is that standard try-catch coding style is possible, just like you were writing synchronous code.

const myFunc = async (req, res) => {
  try {
    const result = await somePromise();
  } catch (err) {
    // handle errors here
  }
};

Here’s an example with Express and promise-mysql. It assumes pool is a promise-mysql pool:

router.get('/flags/:id', async (req, res) => {

  try {

    const connection = await pool.getConnection();

    try {
      const sql = `SELECT f.id, f.width, f.height, f.code, f.filename
                   FROM flags f
                   WHERE f.id = ?
                   LIMIT 1`;
      const flags = await connection.query(sql, req.params.id);
      if (flags.length === 0)
        return res.status(404).send({ message: 'flag not found' });

      return res.send(flags[0]);

    } finally {
      connection.release();
    }

  } catch (err) {
    // handle errors here
  }
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents