Asynchronous Sails.js异步请求
我想数一数某个类别中有多少企业,但我一直坚持异步概念 以下是我已经拥有的:Asynchronous Sails.js异步请求,asynchronous,sails.js,Asynchronous,Sails.js,我想数一数某个类别中有多少企业,但我一直坚持异步概念 以下是我已经拥有的: Category.getall(function(err, cat){ if(err) return res.negotiate(err); catIds = [] for( var iCat in cat){ catIds.push(cat[iCat].id) // and here I would like do something like
Category.getall(function(err, cat){
if(err) return res.negotiate(err);
catIds = []
for( var iCat in cat){
catIds.push(cat[iCat].id)
// and here I would like do something like
Entreprise.count({category_id: cat[iCat].id}, function(err, nbr){
categoriesOUT.push({categorie: cat, entreprise_number: nbr })
// I know that i can not do it but it's just to help to understand the logic I would like to have.
if(cat.length==iCat){
return res.json({categories: categoriesOUT})
}
})
}
})
有两种方法可以解决这个问题。一种是引进一个像这样的承诺图书馆。另一个是单个数据库调用,它可以统计按类别id分组的企业对象。。。但是,我认为这将超出Waterline的正常查询范围,您必须使用.query或.native或其他什么 对你来说,最简单的快速修复方法就是保留一个计数器,记录你处理了多少结果。在多次使用后,您可能会对这种方法感到厌倦,但它看起来是这样的:
Category.getall(function(err, cat){
if(err) { return res.negotiate(err); }
var catIds = [], categoriesOut = [], processedCategories = 0;
for( var iCat in cat){
catIds.push(cat[iCat].id)
Entreprise.count({category_id: cat[iCat].id}, function(err, nbr) {
if (err) {
categoriesOUT.push({categorie: cat, entreprise_number: 0});
} else {
categoriesOUT.push({categorie: cat, entreprise_number: nbr });
}
processedCategories += 1;
if (processedCategories >= cat.length) {
return res.json({categories: categoriesOUT});
}
});
}
});
下面是我最终如何通过@arbuthnott建议的MySQL请求获得它的 类别字段在此处称为域
Domaine.getall(function(err, domaines){
if(err){return res.negotiate(err)}
var domNames = {}, domContain = {}, domOut = [];
Entreprise.query('SELECT domaine_id, COUNT(*) FROM entreprise GROUP BY domaine_id', function(err, entreprises){
if(err){return res.negotiate(err)}
entreprises = JSON.parse(JSON.stringify(entreprises));
for(var ent of entreprises){
domContain[ent['domaine_id']] = ent['COUNT(*)'];
}
for(var iDom in domaines){
var countAdded = false;
for(var dc in domContain){
if(dc==domaines[iDom].id) {
domaines[iDom].entreprises_count = domContain[dc];
countAdded = true;
}
}
if(!countAdded) domaines[iDom].entreprises_count = 0;
}
res.json({domaines:domaines})
})
})