0

I have two models : User, associated by a one-to-many reference with Member.

I want to retrieve the firstName & lastName of User from the Member model, so that I've added a function getName to Member, that would first populate the 'user' field and then return a value when invoked from a template like this :

<p><%= data.members[i].getName() %></p>

But I only get "undefined" in the template (whereas I can print the good values in console from inside the getName function). I guess this is due to the fact that since I have to query the base, getName is going async and returns a Promise.

Here are my models :

/**
* User.js
*/
module.exports = {
  attributes : {
    firstName : 'string',
    lastName : 'string',
  }
}

/**
* Member.js
*/
module.exports = {
  attributes : {
    user : {
      model : 'User'
    },
    getName: function() {
      return Member
        .findOne({ id : this.id })
        .populate('user')
        .exec(function(err, member) {
          if(err) return err;
          return member.user.firstName +' '+ member.user.lastName;
      });
    }
  }
}

Can someone help me by telling me what is wrong with my code ?

P.S. : This might be solved by populating the 'user' field from the controller instead of from the model, but I have another issue like this one that would follow the same principles.

Atopus
  • 35
  • 7
  • It looks like this issue : https://stackoverflow.com/questions/22823796/sails-js-get-async-data-from-an-ejs-file?rq=1 Not very promising in my case... – Atopus Aug 10 '17 at 11:59

1 Answers1

0

Your suspicion is correct -- you can't call asynchronous functions in a view template, because those templates are rendered synchronously. As you stated in your "p.s.", the correct answer is to gather all of your template data in the controller and then send it down to the view in a single object.

sgress454
  • 24,870
  • 4
  • 74
  • 92