我正在看一个博客https://www.acuriousanimal.com/2018/02/15/express-async-middleware.html关于如何处理在Typescript快速路线中等待/异步。
我喜欢使用高阶函数来避免代码冗余的想法,但是
示例代码段:https://gist.github.com/kameshsampath/e550d5bf19feb9b59d0ec1871e59b53a
我相信你想从以下代码中删除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);
}
}));