Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

javascript - 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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The issue here is that you call Client.connect() without an await. Therefore, the async function Clinet.connect() is executed while the function ClientWrapper.connect() has already ended. Add await to the invoke:

await this.client.connect();

then it will work as expected


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...