• guides
  • Express 使用 Async/Await

我使用 node-postgres(以及 node.js 中的所有异步代码)的首选方式是使用 async/await。我发现它使控制流推断变得更容易,并允许我编写更简洁、更易于维护的代码。

¥My preferred way to use node-postgres (and all async code in node.js) is with async/await. I find it makes reasoning about control-flow easier and allows me to write more concise and maintainable code.

这是我通常使用 node-postgres 构建 express web 应用以使用 async/await 的方式:

¥This is how I typically structure express web-applications with node-postgres to use async/await:

- app.js
- index.js
- routes/
  - index.js
  - photos.js
  - user.js
- db/
  - index.js <--- this is where I put data access code

这是我在 项目结构 示例中使用的相同结构。

¥That's the same structure I used in the project structure example.

我的 db/index.js 文件通常以这样的方式开始:

¥My db/index.js file usually starts out like this:

import pg from 'pg'
const { Pool } = pg
 
const pool = new Pool()
 
export const query = (text, params) => pool.query(text, params)

然后我将安装 express-promise-router 并使用它来定义我的路由。这是我的 routes/user.js 文件:

¥Then I will install express-promise-router and use it to define my routes. Here is my routes/user.js file:

import Router from 'express-promise-router'
import db from '../db.js'
 
// create a new express-promise-router
// this has the same API as the normal express router except
// it allows you to use async functions as route handlers
const router = new Router()
 
// export our router to be mounted by the parent application
export default router
 
router.get('/:id', async (req, res) => {
  const { id } = req.params
  const { rows } = await db.query('SELECT * FROM users WHERE id = $1', [id])
  res.send(rows[0])
})

然后在我的 routes/index.js 文件中,我将有类似这样的内容,将每个单独的路由安装到主应用中:

¥Then in my routes/index.js file I'll have something like this which mounts each individual router into the main application:

// ./routes/index.js
import users from './user.js'
import photos from './photos.js'
 
const mountRoutes = (app) => {
  app.use('/users', users)
  app.use('/photos', photos)
  // etc..
}
 
export default mountRoutes

最后,在我引导 express 的 app.js 文件中,我将让我的 routes/index.js 文件挂载我的所有路由。路由知道它们正在使用异步函数,但由于 express-promise-router,主 express 应用不知道也不关心!

¥And finally in my app.js file where I bootstrap express I will have my routes/index.js file mount all my routes. The routes know they're using async functions but because of express-promise-router the main express app doesn't know and doesn't care!

// ./app.js
import express from 'express'
import mountRoutes from './routes.js'
 
const app = express()
mountRoutes(app)
 
// ... more express setup stuff can follow

现在你已经让 async/await、node-postgres 和 express 一起工作了!

¥Now you've got async/await, node-postgres, and express all working together!

Last updated on August 24, 2024