[英]Why is object state not preserved when using Promises?
Consider the following code snippet:考虑以下代码片段:
class ClientWrapper {
private client: Client;
constructor() {
this.client = new Client();
}
async connect() : Promise<void> {
return this.client.connect();
}
async isConnected(): Promise<boolean> {
return this.client.isConnected();
}
};
class Client {
private data?: string;
private connected: boolean;
constructor() {
this.connected = false;
}
isConnected(): boolean {
return this.connected;
}
async connect() : Promise<void> {
this.data = 'data';
const res = await this.executeRequest();
this.connected = true;
}
async executeRequest() : Promise<string> {
return await Promise.resolve(this.data!);
}
};
let wrapper = new ClientWrapper();
(async () => {
await wrapper.connect();
console.log(await wrapper.isConnected());
})();
When executed, line 48 ( console.log(await wrapper.isConnected())
) prints true
.执行时,第 48 行(
console.log(await wrapper.isConnected())
)打印true
。
Now, I modify ClientWrapper
connect()
method to:现在,我将
ClientWrapper
connect()
方法修改为:
async connect() : Promise<void> {
this.client.connect();
}
, removing the return
. ,删除
return
。
Now, line 48 prints false
.现在,第 48 行打印出
false
。
Why does the connected
property of class Client
not preserve the true
value?为什么 class
Client
的connected
属性不保留true
值? Since the connect
method returns Promise<void>
, why does the return
statement matter?既然
connect
方法返回Promise<void>
,为什么return
语句很重要?
Thank you!谢谢!
The issue here is that you call Client.connect()
without an await
.这里的问题是您在没有
await
的情况下调用Client.connect()
。 Therefore, the async function Clinet.connect()
is executed while the function ClientWrapper.connect()
has already ended.因此,异步 function
Clinet.connect()
在 function ClientWrapper.connect()
已经结束时执行。 Add await
to the invoke:在调用中添加
await
:
await this.client.connect();
then it will work as expected然后它将按预期工作
When you return a Promise from an async function, it will be folded into the overall Promise returned from the async function. When you return a Promise from an async function, it will be folded into the overall Promise returned from the async function.
So when you awaited the wrapper.connect
call you were awaiting the inner this.client.connect
call.因此,当您等待
wrapper.connect
调用时,您正在等待内部this.client.connect
调用。
When you removed the return you were awaiting the wrapper.connect
call but it was not synchronised with the inner this.client.connect
call.当您删除返回时,您正在等待
wrapper.connect
调用,但它与内部this.client.connect
调用不同步。 It was basically fire and forget inside the function. function 内部基本上是一劳永逸。
You could also use await this.client.connect()
instead of the return and the behaviour would be the same and makes more sense.您也可以使用
await this.client.connect()
而不是 return 并且行为将相同并且更有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.