简体   繁体   English

将Q promise库与Express.js和Mongoose结合使用

[英]Using Q promise library with Express.js and Mongoose

I've never used promises and am exploring them using an express.js/mongo app I wrote. 我从未使用过Promise,而是使用我编写的express.js / mongo应用程序来探索它们。 Below are one of the routes that query mongo and then set the result as a property on an object in the render method arguments ( to be used by the template engine). 以下是查询mongo,然后将结果设置为render方法参数(由模板引擎使用)中对象的属性的路由之一。 I am curious how to write this in a "promise" style using Q . 我很好奇如何使用Q来以“承诺”的方式编写代码。 I've been fiddling for about an hour and decided to throw in the towel and ask. 我摆弄了大约一个小时,决定扔毛巾问问。

app.get("/", function(req, res) {
    Comment.find(function(err, item) {

        res.render("index", {
            comment: item

        })
    })
})

if you are not persistant that it has to be done on q , you can use bluebird and promisify: 如果您不坚持必须在q上完成操作,则可以使用bluebird并承诺:

var Promise = require("bluebird");
Promise.promisifyAll(Comment);

app.get("/", function(req, res) {
    Comment.find()  // now this is already a promisified method
        .then(function(item){
            res.render("index", { comment: item });
        }).catch(function(err){
            res.render('error', { error: err });
        });
});

I don't think q has such promisification method, so, in q, using deferred : 我不认为q具有这种简化方法,因此在q中使用deferred

var Q = require("q");
app.get("/", function(req, res) {

    var deferred = Q.defer();
    Comment.find(function(err, item) {
        if(err)    return deferred.reject(error);
        deferred.resolve(item);
    });

    deferred.promise
        .then(function(item){
            res.render("index", { comment: item });
        }).catch(function(err){
            res.render('error', { error: err });
        });
});

You'd use Q.ninvoke to get a promise for the item : 您将使用Q.ninvoke获得对该item的承诺:

var itemPromise = Q.ninvoke(Comment, "find");

Now you can chain a .then to that - basically attaching two callbacks: 现在,您可以将.then到该-基本附加两个回调:

itemPromise.then(function(item) {
    // success case
    res.render("index", {
        comment: item
    });
}, function(err) {
    // error case
    res.render("index", {
        comment: undefined // reflecting your original code, but hardly what you want
    });
});

In this case, promises don't have lots of advantage. 在这种情况下,诺言没有太多优势。 You cannot use them for app.get btw, as that might be an asynchronous callback, but for multiple events not for a single result. 您不能将它们用于app.get btw,因为这可能是异步回调,但用于多个事件而不是单个结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM