我有以下简化的中间件功能:
router.put('/', function (req, res, next) {
const data = req.body;
const q = req.parsedFilterParam;
const opts = req.parsedQueryOpts;
ResponseCtrl.update(q, data, opts)
.then(stdPromiseResp(res))
.catch(next);
});
我想为中间件添加一些捕获错误的功能,只是为了节省一些代码,如下所示:
router.put('/', function (req, res, next) {
const data = req.body;
const q = req.parsedFilterParam;
const opts = req.parsedQueryOpts;
return ResponseCtrl.update(q, data, opts)
.then(stdPromiseResp(res));
});
所以我们现在在中间件函数中返回 Promise,并且我们可以放弃 catch block 。
所以在内部,现在可能看起来像这样:
nextMiddlewareFn(req,res,next);
只是想将其更改为:
const v = nextMiddlewareFn(req,res,next);
if(v && typeof v.catch === 'function'){
v.catch(next);
});
有人知道如何使用 Express 做到这一点吗?
最佳答案
var router = new ExpressPromiseRouter();
router.get('/foo', function(req, res) {
return somethingPromisey();
});
// or...
router.get('/bar', async function(req, res) {
await somethingPromisey();
});
app.use(router);
PS:There's no need to be afraid of async
/await
on performance grounds.与带有 Promise 的常规函数没有明显区别。
关于node.js - Express 中间件 - 添加 promise 拒绝处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49415030/