-2

I am trying to run this code, but I get

Avoid referencing unbound methods which may cause unintentional scoping of `this`.eslint@typescript-eslint/unbound-method

on the this.UserLoop and this.RoleLoop. How can I fix this?

export default class Schedule {  
        
    constructor(guild: Discord.Guild) {
        // schedule the benefits to be handed out to patrons
        schedule.scheduleJob(CONFIG.CRON_every_day, this.Benefit.bind(null, guild));
    }

    private async Benefit(guild: Discord.Guild):Promise<void> { // every day
        await Promise.all(DAO_USER.GetAllUsersInGuild(guild.id).map(this.UserLoop));
    }

    private async UserLoop(user: MDL_USER):Promise<void> {
        const ds_user = DAO_USER.GetUserByID(user.GetID());
        const roles = ds_user.GetRoles();
        await Promise.all(roles.map(this.RoleLoop));
    }

    private async RoleLoop(role_id: string):Promise<void> {
        const benefit_function = ACTIONS.mappings[role_id][CONFIG.CRON_every_day].patron_benefit;
        await benefit_function(ds_user);
    }
}
omega
  • 40,311
  • 81
  • 251
  • 474
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – jonrsharpe Jul 26 '20 at 21:46
  • Not really, that fix is to assign this to self, but when I do that I get another issue `Unexpected aliasing of 'this' to local variable.eslint@typescript-eslint/no-this-alias` – omega Jul 26 '20 at 21:48
  • That's *one* of the suggested fixes. Depending on the specific context and your lint rules you may want to pick a different one. – jonrsharpe Jul 26 '20 at 21:49

1 Answers1

0

I have 3 obvious options in mind.

  1. To mark those 2 methods as static and pass static methods instead: static async UserLoop(user: MDL_USER):Promise<void> { and .map(Schedule.UserLoop))
  2. wrap it in a small callback, so this won't be lost: .map(user => this.UserLoop(user)));
  3. make method bound: private UserLoop = async (user: MDL_USER):Promise<void> => {

IMO the 2nd options is the most appropriate

Andrei
  • 10,117
  • 13
  • 21