我的sails.js服务返回“未定义”的调用控制器的行动
我创build了一个名为CategorieService的服务。 它的函数getAllCategorie()应该返回一个对象:
//CategorieService.js module.exports={ getAllCategorie:function() { Categorie.find({where:{statut:'A'},sort:'libelle ASC'}).exec(function(err,categories) { if(categories) { categories.forEach(function(categorie){ console.log('categorie libelle =>'+categorie.libelle); }) return categories; } }) } };
根据需要login控制台显示结果
categorie libelle => car categorie libelle => clothes categorie libelle => rent
但是,当我在我的控制器categorie is undefined
为什么? 和我如何解决它? 低于我的控制器
//ArticleControllerjs var categorie=require('../services/CategorieService'); module.exports = { /*view*/ indexArticle:function(req,res) { var title=req.__('gestiondesarticles.title'); res.view('article',{categories:categorie.getAllCategorie(),title:title,page_name:'article'}); }, }
这是因为所有的数据库访问都是asynchronous的,所以你不能使用categorie.getAllCategorie()
并且需要使用callback函数
你需要做的是:
//CategorieService.js module.exports={ getAllCategorie:function(cb) { Categorie.find({where:{statut:'A'},sort:'libelle ASC'}).exec(function(err,categories) { if(categories) { categories.forEach(function(categorie){ console.log('categorie libelle =>'+categorie.libelle); }) cb(null, categories); } else { cb(err, null); } }) } };
和
//ArticleControllerjs module.exports = { /*view*/ indexArticle:function(req,res) { var title=req.__('gestiondesarticles.title'); CategorieService.getAllCategorie(function(err, categories){ if(categories) { res.view('article',{categories:categories,title:title,page_name:'article'}); } }); }, }
PS:不需要您的服务,Sails已经可以为您提供服务(除非您禁用)