{"library":"middleware-async","title":"Async Express Middleware Wrapper","description":"middleware-async is a utility designed to simplify error handling within asynchronous Express.js or Connect-style middleware. At its stable version 1.4.0, last updated in 2017, it addresses the challenge of correctly propagating errors from `async`/`await` functions or Promises to Express's built-in error handling mechanism. Prior to Express 5.x, unhandled promise rejections in middleware would not automatically be caught by Express and could lead to application crashes. This package provides a wrapper function, `asyncMiddleware`, that catches both synchronous errors and rejected Promises within your middleware, automatically calling `next(err)`. Its release cadence is effectively dormant due to its age and the introduction of native async error handling in modern Express versions. It differentiates itself by offering a straightforward, minimalist solution to avoid repetitive `try...catch` blocks for older Express applications.","language":"javascript","status":"maintenance","last_verified":"Thu Apr 23","install":{"commands":["npm install middleware-async"],"cli":null},"imports":["import asyncMiddleware from 'middleware-async';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import express from 'express';\nimport asyncMiddleware from 'middleware-async';\n\nconst app = express();\n\n// A simulated asynchronous operation\nconst fetchData = () => {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      const success = Math.random() > 0.5;\n      if (success) {\n        resolve({ message: 'Data fetched successfully!' });\n      } else {\n        reject(new Error('Failed to fetch data.'));\n      }\n    }, 500);\n  });\n};\n\n// Define an async middleware that uses fetchData\nconst myAsyncMiddleware = async (req, res, next) => {\n  console.log('Attempting to fetch data...');\n  const data = await fetchData(); // This might reject\n  req.fetchedData = data;\n  next();\n};\n\n// Use the asyncMiddleware wrapper\napp.get('/data', asyncMiddleware(myAsyncMiddleware), (req, res) => {\n  res.json({ status: 'Success', data: req.fetchedData });\n});\n\n// Error handling middleware (must be defined last)\napp.use((err, req, res, next) => {\n  console.error('An error occurred:', err.message);\n  res.status(500).json({ status: 'Error', message: err.message });\n});\n\nconst PORT = process.env.PORT ?? 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Try visiting http://localhost:3000/data multiple times to see success/failure.');\n});","lang":"javascript","description":"Demonstrates wrapping an asynchronous Express middleware with `asyncMiddleware` to catch promise rejections and forward them to Express's error handler, preventing application crashes.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}