简体   繁体   English

为什么使用 Promise 时没有保留 object state?

[英]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 Clientconnected属性不保留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.

相关问题 在灰烬路线中将哈希用于模型时未保留模型对象 - Model object not preserved when using hash for model in ember route 使用promises时为什么最后一次调用? - When using promises why is the last then called? 使用promises时,反应警告无法设置状态 - react warning cannot set state when using promises 使用 Promise 时显示 JS/HTML 按钮状态/状态? - Displaying JS/HTML Button State/Status when using promises? 使用 Promise 时向对象添加数据是线程安全的吗? - Adding data to an object is thread safe when using promises? Object 在 Sequelize 中使用 promise 用于链式承诺时未定义 - Object not defined when using then promise for chained promises in Sequelize 使用Promise从Mongo DB检索对象时出错 - Error when using promises to retrieve object from mongo db 在.when时使用链接的承诺 - Using Chained Promises with .when 无法使用Promise获取对象 - Unable to fetch object using Promises 浏览器后退按钮显示服务器发送的保留页面状态,但是使用javascript完成的所有DOM修改都不会保留 - Browser back-button displays the preserved page state sent by server but any DOM modifications done using javascript is not getting preserved
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM