同时向前端返回多个接口参数
直接上代码
var Q = require('q');
//返回规格
function getGuige() {
var deferred = Q.defer() ;
DB.DB('guige',function (db,collection) {
collection.find({}).sort({time: -1}).toArray(function(err, docs) {
db.close();
if(err){
deferred.reject(err);
}
else{
deferred.resolve(docs);
}
});
})
return deferred.promise;
}
//返回发热量
function getfrl() {
var deferred = Q.defer() ;
DB.DB('fareliang',function (db,collection) {
collection.find({}).sort({time: -1}).toArray(function(err, docs) {
db.close();
if(err){
deferred.reject(err);
}
else{
deferred.resolve(docs);
}
});
})
return deferred.promise;
}
//返回加工工艺
function getjggy() {
var deferred = Q.defer() ;
DB.DB('jiagonggy',function (db,collection) {
collection.find({}).sort({time: -1}).toArray(function(err, docs) {
db.close();
if(err){
deferred.reject(err);
}
else{
deferred.resolve(docs);
}
});
})
return deferred.promise;
}
//返回硫份
function getliufen() {
var deferred = Q.defer() ;
DB.DB('liufen',function (db,collection) {
collection.find({}).sort({time: -1}).toArray(function(err, docs) {
db.close();
if(err){
deferred.reject(err);
}
else{
deferred.resolve(docs);
}
});
})
return deferred.promise;
}
router.get('/good-lists', function(req, res) {
var post = {};
//同时处理多个异步请求
Q.all([getGuige(),getfrl(),getjggy(),getliufen()])
.then(function (resp) {
post.posts = [];
post.frl = [];
post.jggy = [];
post.lf = [];
for(var i = 0;i < resp[0].length;i++){
post.posts.push({name:resp[0][i].name});
}
for(var j = 0;j < resp[1].length;j++){
post.frl.push({name:resp[1][j].name});
}
for(var t = 0;t < resp[2].length;t++){
post.jggy.push({name:resp[2][t].name});
}
for(var k = 0;k < resp[3].length;k++){
post.lf.push({name:resp[3][k].name});
}
console.dir(post);
res.render('good-lists', {
title: '货源信息',
posts: post
});
})
});