节点 js 中的异步中间件处理程序



我已经阅读了承诺/解析/拒绝以及异步/等待。

我想处理异步/等待错误并在 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);
};
}

它只是 ES6 语法。尝试阅读有关 ES6 中如何编写的内容。 fn 是一个函数,作为 asyncMiddleware 函数的参数给出。fn 函数返回一个承诺,该承诺正在该行中解析 Promise.resolve(fn(req, res, next((.如果在fn中遇到任何错误,它将去捕获并处理错误。

希望对您有所帮助。

最新更新