这个问题在这里已有答案:
如何从异步调用返回响应? 31个答案我有非常简单的代码,但我无法理解它。
我有一个返回当前用户名的服务
所以我正在做以下来获取登录的用户名并显示在网页上。 请注意当前登录的用户是“demo”
this.userData.getUsername().then(value => { this.username = value ; console.log("Inside -->" + value); }); console.log("Outside -- >" + this.username);所以现在我运行这段代码。 我没有在this.username中获得用户名
这是console.log的输出 Outside -- >undefined Inside -->demo 在这两种情况下,不要显示“演示”。 (内部和外部)为什么外部未定义?
请帮我理解这个。
This question already has an answer here:
How do I return the response from an asynchronous call? 34 answersI 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.
最满意答案
这是预期的行为。
这是稍后返回的异步调用
this.userData.getUsername().then(value => { this.username = value ; console.log("Inside -->" + value); });在此期间,执行继续进行
console.log("Outside -- >" + this.username);当异步调用最终完成时, Promise执行该函数
value => { this.username = value ; console.log("Inside -->" + value); }那是早先通过的。
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.
更多推荐
发布评论