我是Node js开发的新手。我只是在不久前学习Node js。在这里,我创建一个路由器文件
import express from 'express';
import storyController from '../../controllers/story';
const router = express.Router();
router.post('/', (req, res) => {
const { author, title } = req.body;
console.log(author);
const story = {
author: req.body.author,
title: req.body.title,
content: req.body.content,
tags: req.body.tags
};
storyController.createStory(story, function(error, result){
console.log("halo");
if(error)
res.status(500).send({ success: false, message: error.message});
res.status(200).send({ success: true, message: "Success"});
});
});
然后,我在这里再创建一个称为控制器的文件
import mongoose from 'mongoose';
const Story = mongoose.model('Story');
exports.createStory = async (story) => {
const { author, title } = story;
if(!author){
console.log("hahaAuthor");
return {
error: true,
message: 'You must write an author name!'
};
}
if(!title) {
console.log("haha");
return {
error: true,
message: 'You must write a title!'
}
}
const newStory = new Story({
author: author,
title: title,
content: story.content,
tags: story.tags,
slug: ''
});
newStory.save().then((story) => {
return { error: false, result: story};
}).catch((error) => {
return { error: error};
})
};
但是,不幸的是,我不知道为什么我的路由器文件中的函数没有调用回调函数。 console.log甚至都没有被调用。请帮忙。否则,也许您有更好的方法来做到这一点。谢谢!
答案 0 :(得分:1)
由于createStory
是一个异步函数。像这样更改您的代码。您正在将async
与Promise
和callback
exports.createStory = async (story) => {
...
// Change the promise to await
let story = await newStory.save();
return { error: false, result: story};
};
应该在控制器中使用Promise
catch
子句处理错误。
类似
router.post('/', (req, res) => {
storyController.createStory.then(data => {
return res.json({error: false, data: data});
}).catch(e => {
return res.json({error: true});
})
});
注意:Either use callback or async. async is the best option now adays
答案 1 :(得分:0)
也许可以正常工作
// 1. callback style
newStory.save().then((story) => {
return cb(null, story);
}).catch((error) => {
return cb(error);
})
// 2. await
await newStory.save();
// controller
router.post('/', (req, res) => {
storyController.createStory.then(data => {
return res.json(...);
}).catch(e => {
return res.json(...);
});
如果您使用callback
样式,则Error-First Callback
更好。