BeneosBattlemaps / beneos-module

1 stars 2 forks source link

Bug: `this` is undefined when running on Forge #140

Closed rikmarais closed 3 months ago

rikmarais commented 3 months ago

Hi there, big fan of your work. I've recently assisted a user attempting to debug an issue encountered in version 12.0.1 when running on Forge.

image

From the log there, the error is in https://github.com/BeneosBattlemaps/beneos-module/blob/main/scripts/beneos_utility.js#L72

This happens because the this keyword inside a regular function does not inherit the context from the surrounding code. Instead, it depends on how the function is called. Because an async function is being called from inside a non-async function (and not awaited), by the time the promise completes, this is undefined, leading to the error.

Using an arrow function rather than a regular function after .then should fix it:

let ForgeVTTuserid = ForgeAPI.getUserId()
      ForgeVTTuserid.then((result) => {
        this.beneosBasePath = ForgeVTT.ASSETS_LIBRARY_URL_PREFIX + result + "/";
      });

Arrow functions do not have their own this context; instead, they inherit this from the parent scope, which in this case is the scope where the if statement is located.

Please reach out if you encounter any Forge specific issues and I'll be happy to assist!

LeRatierBretonnien commented 3 months ago

Thanks for pointing this ! I was completely blind :)