Here's a more advanced implementation. Put this in a file called express-p.js:
const express = require('express'); // promise-aware handler substitute function handleP(verb) { return function (...args) { function wrap(fn) { return async function(req, res, next) { // catch both synchronous exceptions and asynchronous rejections try { await fn(req, res, next); } catch(e) { next(e); } } } // reconstruct arguments with wrapped functions let newArgs = args.map(arg => { if (typeof arg === "function") { return wrap(arg); } else { return arg; } }); // register actual middleware with wrapped functions this[verb](...newArgs); } } // modify prototypes for app and router // to add useP, allP, getP, postP, optionsP, deleteP variants ["use", "all", "get", "post", "options", "delete"].forEach(verb => { let handler = handleP(verb); express.Router[verb + "P"] = handler; express.application[verb + "P"] = handler; }); module.exports = express;
Then, in your project, instead of this:
const express = require('express');
use this:
const express = require('./express-p.js');
Then, you can freely use the methods:
.useP() .allP() .getP() .postP() .deleteP() .optionsP()
On either an app object you create or any router objects you create. This code modifies the prototypes so any app object or router objects you create after you load this module will automatically have all those promise-aware methods.