user6571640 user6571640 - 4 months ago 16
Node.js Question

Express.js keep loading and loading when error inside generator

I noticed that while there is an error inside generator, express.js keep processing without stopping it. So, I am not able to find the actual error. My question is: how to stop express.js and output error when there an error in generator.

My codes

Controller.js

const mongoose = require('mongoose');
const {wrap: async} = require('co');
const Post = require('../models/Post');
//.... there are more modules.

const getPosts = async(function* (req, res) {
const page = (req.query.page > 0 ? req.query.page : 1) - 1;
const limit = 5;
const options = {
limit: limit,
page: page
};

const posts = yield Post.list(options);
const count = yield Post.count();
console.log(posts);

res.render('posts/index', {
title: 'Home',
posts: posts,
page: page + 1,
pages: Math.ceil(count / limit)
});
});

app.get('/', getPosts);


Post.js

//.. more codes

postSchema.static.list = function (options) {
const criteria = options.criteria || {};
const page = options.page || 0;
const limit = options.limit || 30;
return this.find(criteria)
.populate('user', 'name userlogin profile email')
.sort({ createdAt: -1 })
.limit(limit)
.skip(limit * page)
.exec();
};

Answer

There is an typo in Post.js. postSchema.static.list should be postSchema.statics.list (statics not static).

Try wrapping yield inside try and catch.

const getPosts = async(function* (req, res, next) {
  const page = (req.query.page > 0 ? req.query.page : 1) - 1;
  const limit = 5;
  const options = {
    limit: limit,
    page: page
  };
  try {
    const posts = yield Post.list(options);
    const count = yield Post.count();
    console.log(posts);

    res.render('posts/index', {
      title: 'Home',
      posts: posts,
      page: page + 1,
      pages: Math.ceil(count / limit)
    });
  }catch(err){
    next(err);
  }
});