在ES2015中,如何确保所有方法都等待对象初始化?使用ES7装饰器

In ES2015 how can I ensure all methods wait for object to initialize ? With ES7 decorators?

本文关键字:初始化 对象 等待 使用 ES7 有方法 ES2015 何确保 确保      更新时间:2023-09-26

我有一个连接到远程服务的ES2015类。

问题是,我的代码试图在这个类的对象完成连接到远程服务器之前访问它。

我想确保,如果对象还没有完成初始化,方法不会只给出错误。

我的类中有很多方法依赖于连接的启动和运行,所以如果有一个简单易懂的机制可以应用于所有方法,比如@sensureConnected decorator,那就太好了。

Fiddle here:https://jsfiddle.net/mct6ss19/2/

'use strict';
class Server {
    helloWorld() {
        return "Hello world"
    }
}
class Client {
    constructor() {
            this.connection = null
            this.establishConnection()
    }
    establishConnection() {
        // simulate slow connection setup by initializing after 2 seconds
        setTimeout(() => {this.connection= new Server()}, 2000)
    }
    doSomethingRemote() {
            console.log(this.connection.helloWorld())
    }
}
let test = new Client();
// doesn't work because we try immediately after object initialization
test.doSomethingRemote();
// works because the object has had time to initialize
setTimeout(() => {test.doSomethingRemote()}, 3000)

我使用ES7装饰器来实现一个测试,看看连接是否建立,但我不知道如何做到这一点

我不会在构造函数中启动连接。构造函数更多地是为初始化变量等而设计的,而不是程序逻辑。相反,我会从您的客户端代码中自己调用establishConnection

如果要在构造函数中执行此操作,请将结果存储在实例变量中,然后在doSomethingRemote中等待,如:

class Client {
    constructor() {
        this.connection = this.establishConnection();
    }
    establishConnection() {
        // simulate slow connection setup by initializing after 2 seconds
        return new Promise(resolve => setTimeout(() =>
          resolve(new Server()), 2000));
    }
    doSomethingRemote() {
        this.connection.then(connection => connection.helloWorld());
    }
}

最后,我尝试了一系列解决方案,包括decorator和使用代理对象。

我想要的解决方案是使用ES7异步和等待。经过一番摸索,试图了解它是如何工作的,以及如何解决问题,终于让它发挥了作用。

因此,异步和等待是我确保对象正确初始化的最有效的解决方案。

我还听取了@torazaburo的建议(见本页其他地方的回答),并从一个工厂运行了初始化方法,该工厂首先创建并初始化了对象。