2016-07-24 72 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.list應該是postSchema.statics.list(靜態不是靜態的)。

嘗試包裝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

相關問題