"this" 在嵌套的异步模块函数中如何正常运行?

How would "this" behave normally within nested async module functions?

我正在使用 Sails.js 框架及其出色的 Model 功能,同时我正在使用它用作依赖项的 async 版本。

因此,为了解释一个实际场景:获取对艺术家演唱的歌曲的所有评论。我应该先查询歌曲再查询评论

这就是我使用 async 模块的原因,特别是它的 waterfall 功能。但是由于所有这些代码都放在一个模型文件中,其中 this 指的是模型本身,我有一个很大的疑问:

即使存在于异步函数中,它是否也始终引用模型?

这是我正在做的代码示例:

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

    reachesMaxFavoriteTeam: function (team) {

      var results [];

      async.waterfall([

          // Get favorite team
          function (cb) {
              var userTeam = this.userTeam;

              UserTeam.findOne({_id: userTeam}, function (err, foundUserTeam) {
                  if (err)
                      cb(err,null);
                  var user = foundUserTeam.user;
                  User.find({_id: user}, {_id:false, fanOf: true}, function (err, fanOf) {
                      if (err)
                          cb(err,null);
                      cb(null,fanOf.name);
                  });
              });
          },
          // Check if it reaches a max favorite team error
          function (favoriteTeam,cb) {

              // If player to be added is from favorite team, it counts.
              favoriteCount = team === favoriteTeam ? 1: 0;

              // Check if any of added players are from favorite team too.
              _.forEach(this.players, function (player) {

                  var playerTeam = player.team.name;

                  if (playerTeam === favoriteTeam)
                      favoriteCount++;
              });


              return favoriteCount > process.env.CONDITION;
          }]);
    }
};

因此,例如,在瀑布系列的第一个函数中,我得到:var userTeam = this.userTeam;,它会按预期工作吗?如果有其他嵌套函数,我应该处理一些事情吗?

为什么不在这些查询中使用 Promises 将使它更容易使用。我不会使用异步,使用 Promises 应该可以完成这项工作。

Sails 中的底层 ORM 模块是 Waterline。您可以参考 Chaining waterline calls with Promises for an example or the GitHub page https://github.com/balderdashy/waterline 显示以下示例,

User.findOne()
.where({ id: 2 })
.then(function(user){
    var comments = Comment.find({userId: user.id}).then(function(comments){
        return comments;
    });
   return [user.id, user.friendsList, comments];
}).spread(function(userId, friendsList, comments){
// Promises are awesome!
}).catch(function(err){
// An error occurred
})

Waterline-docs 也有助于参考:https://github.com/balderdashy/waterline-docs