-1

Easy question. Just an explict look:

 var token = "12345"

function einloggen(){
    var test = particle.login({username: userName, password: passWord});
    test.then(
    function (data) {
            token = data.body.access_token;
            console.log('tokenoutprint1:', token);
            },
    function (err) {
            console.log('LoggingIn Failed', err);
            }
);
console.log('tokenoutprint2:', token);

}
einloggen();

after that i want to reuse the "new" token in a different Function...

callFunctionAVC(token);

The third last line will print me 12345. But I want print out the "new" token, defined in. Like in "normal" java

I don't know why because the first console.log shows me the right token.

SO HOW DO I GET THE "TOKEN" TO A GLOBAL VARIABLE. Thats my "real" Question. Please send full codes only otherwise i won't get it.

Sorry for not being a pro, I'm just learning in school.

Greetings.

F3IIX8
  • 7
  • 4
  • because you're using a promise its async therefore once the request is done it starts exicuting the non async function until its request is resolved or rejected it will have changed token just not when it console logs it – Joe Warner Jun 01 '18 at 12:45
  • are you calling the function `einloggen` anywhere? – seethrough Jun 01 '18 at 12:45
  • but i need it to be changed first cause i want to reuse that var in another function. – F3IIX8 Jun 01 '18 at 12:46
  • sure its just an explicit – F3IIX8 Jun 01 '18 at 12:46
  • @F3IIX8 call that other function from within promise then, just after you change token – seethrough Jun 01 '18 at 12:47
  • whats promise?? im new... sry – F3IIX8 Jun 01 '18 at 12:48
  • @F3IIX8 call your function after this code `token = data.body.access_token; console.log('token', token);` just where you call console.log, or after it – seethrough Jun 01 '18 at 12:49
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Jun 01 '18 at 13:49

1 Answers1

-1

The einloggen function is not (visibly) being called before the console.log, which means you set token = "12345", console.log() it and some time later you may or may not call the einloggen function.

I think what you wanted to do is:

function einloggen() {
    //your code
}
einloggen(); // Execute the method
console.log(token);

There's a possibility this won't work as expected as well because you're using Promises in your einloggen function.

You could also try to execute console.log(token) from the developer console of your browser.

Ahmed Bajra
  • 391
  • 1
  • 2
  • 14