我写的两个函数类似,但一个(其中有using then后保存())是不工作,另一个是工作,我使用异步/等待
这是工作
exports.update = async(req, res) => {
const slug = req.params.slug.toLowerCase();
try {
let oldBlog=await Blog.findOne({ slug }).exec();
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, async(err, fields, files) => {
if (err) {
return res.status(400).json({
error: 'Image could not upload'
});
}
let { title, body, categories, tags } = fields;
let { photo } = files;
title = title && title[0];
body = body && body[0];
categories = categories && categories[0];
tags = tags && tags[0];
photo = photo && photo[0];
let slugBeforeMerge = oldBlog.slug;
oldBlog = _.merge(oldBlog, {title,body, categories, tags, photo});
oldBlog.slug = slugBeforeMerge;
if (body) {
oldBlog.excerpt = smartTrim(body, 320, ' ', ' ...');
oldBlog.desc = stripHtml(body.substring(0, 160));
}
if (categories) {
oldBlog.categories = categories.split(',');
}
if (tags) {
oldBlog.tags = tags.split(',');
}
if (photo) {
if (files.photo.size > 10000000) {
return res.status(400).json({
error: 'Image should be less then 1mb in size'
});
}
oldBlog.photo.data = fs.readFileSync(photo.filepath);
oldBlog.photo.contentType = photo.mimetype;
}
const result=await oldBlog.save();
res.json(result);
});
} catch (err) {
return res.status(400).json({
error: errorHandler(err)
});
}
};
字符串
这个不行
exports.update = (req, res) => {
const slug = req.params.slug.toLowerCase();
Blog.findOne({ slug })
.exec()
.then((oldBlog) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
if (err) {
return res.status(400).json({
error: 'Image could not upload',
});
}
let { body, title, categories, tags } = fields;
let { photo } = files;
title = title && title[0];
body = body && body[0];
categories = categories && categories[0];
tags = tags && tags[0];
photo = photo && photo[0];
let slugBeforeMerge = oldBlog.slug;
oldBlog=_.merge(oldBlog, {title,body,categories, tags, photo});
oldBlog.slug = slugBeforeMerge;
if (title) {
oldBlog.title = title;
}
if (body) {
oldBlog.excerpt = smartTrim(body, 320, ' ', ' ...');
oldBlog.desc = stripHtml(body.substring(0, 160));
}
if (categories) {
oldBlog.categories = categories.split(',');
}
if (tags) {
oldBlog.tags = tags.split(',');
}
if (photo) {
if (photo.size > 10000000) {
return res.status(400).json({
error: 'Image should be less then 1mb in size',
});
}
oldBlog.photo.data = fs.readFileSync(photo.filepath);
oldBlog.photo.contentType = photo.mimetype;
}
});
return oldBlog.save();
})
.then((result) => res.json(result))
.catch((err) =>
res.status(400).json({
error: errorHandler(err),
})
);
};
型
请有人告诉我,我在下面的代码块错误,所以不工作
我想知道为什么then/catch代码不工作,而async/await工作,并且两个代码非常相似
1条答案
按热度按时间a1o7rhls1#
我正在缩短你的代码,排除不相关的部分:
字符串