具有Express路由的高阶函数

问题描述 投票:0回答:1

我正在看一个博客https://www.acuriousanimal.com/2018/02/15/express-async-middleware.html关于如何处理在Typescript快速路线中等待/异步。

我喜欢使用高阶函数来避免代码冗余的想法,但是

  1. 我不知道如何在TypeScript中做到这一点
  2. TypeScript是否有其他更好的方法可用于此类场景

示例代码段:https://gist.github.com/kameshsampath/e550d5bf19feb9b59d0ec1871e59b53a

node.js typescript express
1个回答
0
投票

我相信你想从以下代码中删除catch到更高阶函数:

app.get("/api/frames", async (req: Request, res: Response, next: any) => {
  //TODO move this to higher order function
  try {
    const qCollection = await loadCollection("frames", db);
    const docs = qCollection.find();
    if (docs) {
      return res
        .contentType("json")
        .status(200)
        .send(docs);
    }
  } catch (err) {
    res.status(404).send(err);
  }
    app.get("/api/frames", async (req: Request, res: Response, next: any) => {
  //TODO move this to higher order function
  try {
    const qCollection = await loadCollection("frames", db);
    const docs = qCollection.find();
    if (docs) {
      return res
        .contentType("json")
        .status(200)
        .send(docs);
    }
  } catch (err) {
    res.status(404).send(err);
  }
});

这样做:

const asyncHandler = fn => (req, res, next) =>
  Promise
    .resolve(fn(req, res, next))
    .catch((err)=>res.status(404).send(err);)

app.get("/api/frames", asyncHandler(async (req: Request, res: Response, next: any) => {
    const qCollection = await loadCollection("frames", db);
    const docs = qCollection.find();
    if (docs) {
      return res
        .contentType("json")
        .status(200)
        .send(docs);
    }
 }));
© www.soinside.com 2019 - 2024. All rights reserved.