使用async / await与mongoose.js

时间:2018-04-03 04:25:41

标签: express mongoose async-await

寻求帮助,使用async / await重写这两个查询,而不是使用嵌套的回调方法。

exports.post_edit_get = function(req, res, next) {
    var id = req.params.id;
    if (mongoose.Types.ObjectId.isValid(id)){
        POST.findById(id, function (err, doc){
            if (err) { return next(err); }
            playerQuery.exec(function (err, players){
                if (err) { return next(err); }
                res.render('posts/posts_admin', { title: pageTitle, formData: doc, players: players });
            });
        });
    }else{
        res.send("Invalid ID");
    };
};

1 个答案:

答案 0 :(得分:2)

你去吧

const { isValid } = mongoose.Types.ObjectId

exports.post_edit_get = async function(req, res, next) {
    var { id } = req.params;

    if (!isValid(id)){
        return res.send("Invalid ID");        
    }

    try {
        const post = await POST.findById(id)
        const players = await playerQuery.exec()

        res.render('posts/posts_admin', { 
            title: pageTitle, 
            formData: doc, 
            players: players 
        })
    } catch (err) {
        return next(err)        
    }
}

如果你想在路线处理程序级别摆脱这些尝试/捕获,你会想看看这篇文章; Using async/await to write cleaner route handlers