首页 > 解决方案 > 节点 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);
}));

标签: javascriptnode.jsasynchronouspromiseasync-await

解决方案


它与以下内容相同:

// asyncMiddleware is function that returns another function
const asyncMiddleware = function(fn){
  return (req, res, next) => {
    Promise.resolve(fn(req, res, next))
      .catch(next);
  };
}

推荐阅读