2016-07-24 3 views
1

ジェネレータ内にエラーがある間、express.jsは処理を停止せずに継続します。したがって、私は実際のエラーを見つけることができません。私の質問は、どのようにexpress.jsを停止し、ジェネレータにエラーが発生したときに出力エラーを出すかです。Express.jsはジェネレータ内部でエラーが発生したときに読み込みとロードを続けます

マイコード

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

答えて

1

Post.js.にタイプミスがありますpostSchema.static.listpostSchema.statics.list(静的ではない統計情報)にする必要があります。

tryとcatchの内側にyieldをラップしてみてください。

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

私はとても愚かです。どうもありがとう。 – user6571640

関連する問題