Variable out of scope?
-
Hello to all,
I am trying to implement an online license activation using the developer's HISE demo code.
When I split the code into multiple functions as suggested by the developer, the function “getUserLicense” does not see the “token” variable or it is not defined in this function. If I put everything in one function, it works.
Does anyone know why this is the case?
Thank you very much
Oli// Declare Variables var payload; var token; // Setting the Base URL Server.setBaseURL("https://demo.firassaidi.com/wc-license-manager"); // Retrieve the JSON Web Token (JWT) inline function getJSONWebToken(username, password) { payload = { "username": username, "password": password }; Server.callWithPOST('/wp-json/jwt-auth/v1/token', payload, function(status, response) { token = response.token; Console.print("Token: " + token); }); } // Fetch User Licenses inline function getUserLicense() { if (isDefined(token)) { Server.setHttpHeader("Authorization: Bearer " + token); Server.callWithPOST('/wp-json/wclm/v3/get-current-user-licenses', {}, function(status, response) { Console.print(trace(response)); }); } } // Functioncalls if(Server.isOnline()) { getJSONWebToken("demo", "demo"); getUserLicense(); }
-
@Oli-Ullmann Don't use
var
unless it's the only choice. Usereg
orconst
as appropriate.getUserLicense
is being called inon init
before a value has been assigned to thetoken
variable, so it will be undefined. Assign a default value to it and then the error should go away. -
This post is deleted! -
@d-healey
Hey David,
in my project I actually use reg.token = response.token;
this line assigns a value to the “token” variable in the getJSONWebToken() function that is called before, doesn't it?
-
@Oli-Ullmann said in Variable out of scope?:
that is called before, doesn't it?
It's called before, but that function is calling a server which takes time to get a response, in the meantime your
getUserLicense
function has already been called. -
@d-healey Ah ok, do you see a way to execute the getUserLicense() function only after the response of the getJSONWebToken() function is there?
-
@Oli-Ullmann Call it from within the other function
-
@d-healey Yes, that was my approach too. I thought there was a better way. But then I do it this way. Thanks to you! :-)