1

I have very simple code , But I am not able to understand it.

I have a service which returns current Username

so I am doing following to get logged username and display on webpage. Please note current logged in user is "demo"

 this.userData.getUsername().then(value  => {
this.username = value ;   
console.log("Inside -->" + value);
});
console.log("Outside -- >" + this.username);

So now when I run this code. I do NOT get username in this.username

This is the output of console.log
Outside -- >undefined Inside -->demo
Shoulnd't this display 'demo' in both case. (inside and outside) Why outside is undefined ??

Please help me understand this.

viks
  • 57
  • 3
  • 1
    It's because the call is asynchronous. It's starts running the `getUsername()` method, but while it's running it continues on. So it hits the Outside log first, where `this.username` is still undefined, then the method finishes and you get the Inside log – Dave V Oct 20 '16 at 15:54
  • Its nothing related to Angular 2. This is how asynchronous call works, [read more here](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests) – Pankaj Parkar Oct 20 '16 at 15:56

1 Answers1

2

This is the expected behavior.

This is an async call that returns later

this.userData.getUsername().then(value  => {
  this.username = value ;   
  console.log("Inside -->" + value);
});

In the meantime execution continues here

console.log("Outside -- >" + this.username);

When the async call completes eventually the Promise executes the function

value  => {
  this.username = value ;   
  console.log("Inside -->" + value);
}

that was passed earlier.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks. then how do I get username in global variable (this.username) ? – viks Oct 20 '16 at 15:57
  • 1
    This is what your code is doing already. What you seem to be confused about is what happens when. `this.username = value;` is executed much later then `console.log("Outside -- >" + this.username);` – Günter Zöchbauer Oct 20 '16 at 15:59
  • 1
    Got it. I just got confused and did not code next step. I am actually getting correct value in the variable. Should have just trusted myself . – viks Oct 20 '16 at 16:02