【发布时间】:2020-01-02 05:14:48
【问题描述】:
我想知道如何在 async/await 中工作,如果在 async/await 中 try-catch 更方便,或者只使用 then-catch 的 Promise 而不使用 async-await
我以 Node JS 和 Express 中的这段小代码为例,以便更好地理解:
const { validationResult } = require('express-validator');
const Post = require('../models/post');
module.exports = {
//HTTP POST Method
createPost: async(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({
errors: errors.array()[0].msg
});
}
try {
const { title, content, imageUrl } = req.body;
const newPost = new Post({
title,
content,
imageUrl
});
const post = await newPost.save();
if (!post) {
return res.status(422).json({
errors: 'Error'
});
}
return res.status(201).json({
message: 'Post created successfully!',
post: {
title: title,
content: content,
image: imageUrl,
}
});
} catch (err) {
return res.status(500).json({
errors: 'Error'
});
}
}
}
感谢您的宝贵时间!
【问题讨论】:
-
我不清楚你在问什么。
try/catch将在await上捕获同步抛出的异常或被拒绝的承诺。你能把你的问题说得更具体一点吗?你问的是哪几行代码? -
仅供参考,您的
if (!post) ...声明可能永远不会被触发。如果.save()失败,它可能会拒绝,而不是使用null解决。来自await的拒绝将转到您的catch()。 -
@jfriend00 我想知道如何在 async/await 中工作,如果在 async/await 中 try-catch 更方便,或者只使用 Promise 而不使用 async-await,只使用 Promise然后抓住。
标签: node.js async-await try-catch