在node.js中使用promise链接数据库查询

我试图使用spread方法来积累我已经读过的Q.js在这个线程中承诺的结果。 它在另一个代码块中工作,但不在下面的app.get例子中。 我想链接查询使用Sequelizemongoose和传递所有返回的数据传播的方法。 这是我的尝试:

 var db = require('./db/managedb'); // Sequelize var mongo_models = require('./db/mongo_model')(mongoose); var WB = mongo_models.Webdata, Est = mongo_models.Estimate; app.get('/p/:tagId', function(req, res){ var filename = req.param("tagId"); var mysql = db.db.query('CALL procedure()').then(function(rows) { console.log(rows); }); // Sequelize var nosql = WB.find().exec(function(err,k){ console.log(k); }) // Mongoose var nosql2 = Est.find().exec(function(err,la){ console.log(la); }) // Mongoose Q.try(function(){ return mysql }).then(function(mysqls){ return [ mysqls,nosql] }).then(function(mysqls,nosqls){ return [mysqls,nosqls,nosql2] }).spread(function(mysqls,nosqls,nosql2s){ res.render(filename+'.html', {my:mysqls,wb:nosqls,est:nosql2s}) }).catch(function(error){ console.log('fail') }) }) 

我只是得到一个空白页面Cannot GET /p/5 ,没有“失败”显示在console.log。 这是我的原始代码,但它是从callback地狱痛苦。

 app.get('/p/:tagId', function(req, res){ var filename = req.param("tagId"); db.db.query('CALL procedure()').then(function(rows) { WB.find().exec(function(err,wb){ Est.find().exec(function(err,est){ res.render(filename+'.html', {my:rows,wb:wb,est:est}) }) }) }).catch(function (error) { console.log('own: database error'); }) }) 

你可以尝试使用它们作为代理:

 app.get('/p/:tagId', function(req, res){ var filename = req.param("tagId"); var rows = db.db.query('CALL procedure()'); var wb = WB.find().exec(); var est = Est.find().exec(); Promise.props({my: rows, wb: wb, est: est}).then(function(obj){ res.render(filename+'.html', obj) }).catch(function (error) { console.log('own: database error'); // not sure I'd just supress it }); }); 

如果你没有在你的项目中使用蓝鸟,那么蓝鸟已经可以使用了。

或者,你不必把它们放在特定的variables中:

 app.get('/p/:tagId', function(req, res){ var filename = req.param("tagId"); Promise.props({ my: db.db.query('CALL procedure()'), wb: WB.find().exec(), est: Est.find().exec() }).then(function(obj){ res.render(filename+'.html', obj); }).catch(function (error) { console.log('own: database error'); // not sure I'd just supress it }); });