0

I'm a newbie in node js Development. I just learn node js in short time ago. 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. Please help. Otherwise, maybe you have a better way to do this. Thanks!

2
  • 3
    Your createStory does not accept a callback parameter. Commented Oct 8, 2018 at 4:42
  • Yeah, thank you so much! that's the answer. Shouldn't you post that as an answer? or should I answer by myself? Commented Oct 8, 2018 at 4:43

2 Answers 2

1

As createStory is an async function. Change your code like this. You are mixing async with Promise and callback

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.

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

Sign up to request clarification or add additional context in comments.

2 Comments

Then, using your code how can I take the error message from newStory.save() ??
You can get the error message in the catch in controller. Please change the code in to correct folder structure. For details viswanathl.in/2017/05/09/how-to-node-for-real-world-application
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.