除非包装,否则可以在功能上调用.catch。
我具有这样的异步函数
router.get("/", async function (req, res, next) {
const posts = await Post.find({});
res.render("index", { title: "Homepage", posts });
});
,我可以将其包装在处理捕获量的函数中
function catchAsync(fn) {
return function (req, res, next) {
fn(req, res, next).catch((e) => next(e));
};
}
,因此看起来像这样
router.get(
"/",
catchAsync(async function (req, res, next) {
const posts = await Post.find({});
res.render("index", { title: "Homepage", posts });
})
);
,但我的疑问和此帖子的原因是为什么我不能直接在异步函数上拨打。 ,这样吗?
router.get(
"/",
async function (req, res, next) {
const posts = await Post.find({});
res.render("index", { title: "Homepage", posts });
}.catch((e) => next(e))
);
我了解我可以做到这一点
router.get("/", async function (req, res, next) {
my_callback(req, res, next).catch((e) => {
next(e);
});
});
let my_callback = async function (req, res, next) {
const posts = await Post.find({});
res.render("index", { title: "Homepage", posts });
};
I have an async function such as this
router.get("/", async function (req, res, next) {
const posts = await Post.find({});
res.render("index", { title: "Homepage", posts });
});
and I can wrap it in a function that handles its catch
function catchAsync(fn) {
return function (req, res, next) {
fn(req, res, next).catch((e) => next(e));
};
}
so it looks like this
router.get(
"/",
catchAsync(async function (req, res, next) {
const posts = await Post.find({});
res.render("index", { title: "Homepage", posts });
})
);
but my doubt, and the reason for this post, is why can't I call .catch directly on the async function, like so?
router.get(
"/",
async function (req, res, next) {
const posts = await Post.find({});
res.render("index", { title: "Homepage", posts });
}.catch((e) => next(e))
);
I understand I can do this however
router.get("/", async function (req, res, next) {
my_callback(req, res, next).catch((e) => {
next(e);
});
});
let my_callback = async function (req, res, next) {
const posts = await Post.find({});
res.render("index", { title: "Homepage", posts });
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里,您是在
上调用
返回 by 呼叫.catch
promisemy_callback
函数在这里您尝试访问
.catch
定义 ,这是语法上是错误的在JavaScript中,如果要包含
catch
和函数定义,则可以使用尝试...捕获更多地阅读有关承诺的阅读 - https://deverveper.mozilla.org/en-us/docs/docs/web/javascript/reference/global_obabled/global_objects/promise
Here you are calling
.catch
on aPromise
returned by callingmy_callback
functionHere you are trying to access
.catch
on a function definition which is syntactically wrong in JavaScriptIf you want to include
catch
with the function definition then you can use try...catchMore reading about promises - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise