R
Rishtaara
Node.js Fundamentals
Lesson 7 of 8Article18 min

Async Patterns and Database Access

Most backend operations are asynchronous: database calls, external APIs, and file services. Use async/await with try/catch for readable control flow and safer error propagation.

Async/await in real handlers

Most backend operations are asynchronous: database calls, external APIs, and file services. Use async/await with try/catch for readable control flow and safer error propagation.

Async route with repository function
async function getCourseById(id) {
  // pretend this is a DB call
  return { id, title: "Node.js Fundamentals" };
}

app.get("/api/courses/:id", async (req, res, next) => {
  try {
    const course = await getCourseById(req.params.id);
    if (!course) return res.status(404).json({ error: "Not found" });
    res.json({ data: course });
  } catch (error) {
    next(error);
  }
});

Database integration principles

  • Use connection pooling, not per-request new connections.
  • Validate and sanitize input before persistence.
  • Wrap multi-step state changes in transactions when supported.
  • Log slow queries and timeouts.