Hari Setiawan
Hari Setiawan

Reputation: 136

Node JS Callback function return nothing

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!

Upvotes: 0

Views: 737

Answers (2)

polunzh
polunzh

Reputation: 318

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.

Upvotes: 0

Viswanath Lekshmanan
Viswanath Lekshmanan

Reputation: 10083

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

Upvotes: 1

Related Questions