How to properly use waterline promises in model's attribute method?

213 views Asked by At

In a Model I'm using attribute methods which will lookup against database, having to query against other distinct models.

So I use waterline promises but I got not sure HOW to actually perform the return method FOR THE model's attribute method itself, this is what I'm doing:

Let's call it a LineUp model:

module.exports = {
  connection: 'seasonDB',
  attributes: {

    reachesMaxFavoriteTeam: function (team) {

      UserTeam.findOne().
        where({id: this.userTeam}).
        then(function (team) {
          User.findOne().
            where({id: team.userId}).
            then(function (user) {
              return [team, user.fanOf];     // I assume to be returning  for the spread function
            }).
            spread(function (team, user) {
               // How can I make reachesMaxFavoriteTeam return something here???
            }).catch(function (err) {

            });
        });
    }
};

So I got not clue how and even where I should perform a return for the reachesMaxFavoriteTeam attribute method for LineUp itself.

1

There are 1 answers

1
robertklep On

You return the entire promise chain:

reachesMaxFavoriteTeam: function (team) {
  return UserTeam.findOne().
    where({id: this.userTeam}).
    then(function (team) {
      User.findOne().
        where({id: team.userId}).
        then(function (user) {
          return [team, user.fanOf];
        }).
        spread(function (team, user) {
          return THE_RESULT;
        }).catch(function (err) {

        });
    });
}

Your calling code:

lineUpInstance.reachesMaxFavoriteTeam(team).then(function(result) {
  // result === THE_RESULT here
});