简体   繁体   English

节点JS回调函数不返回任何内容

[英]Node JS Callback function return nothing

I'm a newbie in node js Development. 我是Node js开发的新手。 I just learn node js in short time ago. 我只是在不久前学习Node js。 Here I create a router file 在这里我创建一个路由器文件

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"});
  });
});

Then, i create one more file referred as the controller here 然后,我在这里再创建一个称为控制器的文件

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};
 })
};

But, unfortunately I don't know why my function in router file doesn't call the callback function. 但是,不幸的是,我不知道为什么我的路由器文件中的函数没有调用回调函数。 The console.log doesn't even called yet. console.log甚至都没有被调用。 Please help. 请帮忙。 Otherwise, maybe you have a better way to do this. 否则,也许您有更好的方法来做到这一点。 Thanks! 谢谢!

As createStory is an async function. 由于createStory是一个异步函数。 Change your code like this. 像这样更改您的代码。 You are mixing async with Promise and callback 您正在将asyncPromisecallback混合在一起

exports.createStory = async (story) => {
    ...
    // Change the promise to await
    let story = await newStory.save();
    return { error: false, result: story};
};

Error should be handled in the controller with Promise catch clause. 应该在控制器中使用Promise catch子句处理错误。

Something like 就像是

router.post('/', (req, res) => {
    storyController.createStory.then(data => {
        return res.json({error: false, data: data});
    }).catch(e => {
        return res.json({error: true}); 
    })
});

Note: Either use callback or async. async is the best option now adays 注意: Either use callback or async. async is the best option now adays Either use callback or async. async is the best option now adays

May be this can work: 可能这可以工作:

// 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(...); 
});

If you use callback style, Error-First Callback is better. 如果使用callback样式,则“ Error-First Callback会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM