viks viks - 1 month ago 21
Javascript Question

Confused about Angular2 promise

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.

Answer

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.