Pisix
Pisix

Reputation: 205

My sails.js service return “undefined” to the calling controller action

I created a service called CategorieService. Its function getAllCategorie() is supposed to return an object:

    //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;
             }
        })
    }
};

log in console show result as I want

categorie libelle => car
categorie libelle => clothes
categorie libelle => rent

But When in my controllercategorie is undefined why ? and How can I fix it ? below my controller

//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'});

        },
    }

Upvotes: 2

Views: 918

Answers (1)

jaumard
jaumard

Reputation: 8292

It's because all database access are asynchronous, so you can't use categorie.getAllCategorie() and need to use callbacks

You need to do :

//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);
             }
        })
    }
};

And

//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 : No need to require your service, Sails already make it available for you (except if you disable it)

Upvotes: 3

Related Questions