对Angular2承诺感到困惑[重复](Confused about Angular2 promise [duplicate])

编程入门 行业动态 更新时间:2024-10-24 10:26:35
对Angular2承诺感到困惑[重复](Confused about Angular2 promise [duplicate])

这个问题在这里已有答案:

如何从异步调用返回响应? 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 answers

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.

最满意答案

这是预期的行为。

这是稍后返回的异步调用

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.

更多推荐

本文发布于:2023-08-04 09:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415321.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:困惑   Confused   duplicate   promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!