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
.
Now, I modify ClientWrapper
connect()
method to:
async connect() : Promise<void> {
this.client.connect();
}
, removing the return
.
Now, line 48 prints false
.
Why does the connected
property of class Client
not preserve the true
value? Since the connect
method returns Promise<void>
, why does the return
statement matter?
Thank you!
question from:
https://stackoverflow.com/questions/66064632/why-is-object-state-not-preserved-when-using-promises 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…