async-middleware is a utility package designed to simplify error handling for asynchronous middleware functions within web frameworks like Express and Connect. It wraps an `async` or Promise-returning function, automatically catching rejected Promises and forwarding the error to the `next(err)` callback, preventing uncaught Promise rejections from crashing the application. The package is currently at version 1.2.1 and appears to be in a maintenance state, with the last release being in 2017 focusing on minor fixes and dependency cleanups rather than new features. Its key differentiator is its singular focus on robust async error piping for traditional middleware stacks, providing a lightweight alternative to more comprehensive async libraries. It ships with TypeScript types, enhancing developer experience for type-safe applications.
npm install async-middlewareVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates wrapping both resolving and rejecting asynchronous Express middleware functions, showcasing how 'async-middleware' automatically pipes Promise rejections to the Express error handler.
Ensure your asynchronous middleware functions explicitly return Promises or are `async` functions. If you need to convert a non-Promise value, do so explicitly (e.g., `Promise.resolve(value)`) before returning it.
For older environments, ensure a Promise polyfill is globally available before `async-middleware` is initialized (e.g., `require('core-js/es6/promise')` or similar).Ensure `typeRoots` in your `tsconfig.json` includes `node_modules/@types` or simply remove `typeRoots` to allow TypeScript to discover `@types` automatically if you are not using custom type roots.
Always reject Promises with an `Error` instance (e.g., `Promise.reject(new Error('message'))`) to provide meaningful error information in your error handling middleware.Use `const { wrap } = require('async-middleware');` for CommonJS or `import { wrap } from 'async-middleware';` for ESM.Ensure that your Promises consistently reject with `Error` objects. For example, instead of `Promise.reject({ code: 500 })`, use `Promise.reject(new Error('Internal Server Error'))`.No dependency data recorded yet.