javascript - 节点 js 中的 AsyncMiddleware 处理程序
问题描述
我已经阅读了 promise/resolve/reject 以及 async/await。
我想处理 async/await 错误并在medium.com上找到了一个代码,但我无法理解它到底做了什么。
任何人都可以尝试解释以下代码的工作原理:
a)fn
这里有什么?
b)我实际上无法理解以下块中的任何代码。
const asyncMiddleware = fn =>
(req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
并使用它如下:
router.get('/users/:id', asyncMiddleware(async (req, res, next) => {
/*
if there is an error thrown in getUserFromDb, asyncMiddleware
will pass it to next() and express will handle the error;
*/
const user = await getUserFromDb({ id: req.params.id })
res.json(user);
}));
解决方案
它与以下内容相同:
// asyncMiddleware is function that returns another function
const asyncMiddleware = function(fn){
return (req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
}
推荐阅读
- python - 如何使用字典作为量规来使用 pd.apply() 为数据框分配值
- rust - 有没有办法在使用 Serde 反序列化对象时省略包装器/根对象?
- eclipse - CVS 忽略 .git 文件夹
- python - 将代码转换为 python 3,其中 str 和 bytes 不能再连接
- amazon-ec2 - 在 Jupyter 笔记本中禁用“上传”
- json - 编码适用于 1 而不是 Twitter 中使用 python 的其他列表
- reactjs - How to pass extra params to frameworkComponents
- reactjs - 反应表单未填写获取的数据
- python - 在 Pandas 中创建 DataFrame 时填充默认值 0
- javascript - 有没有办法将具有多个 if 语句的函数转换为箭头函数?