gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:01:41 24 4
gpt4 key购买 nike

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

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

我想确保方法不会在对象尚未完成初始化时给出错误。

我的类(class)中会有很多方法依赖于连接的启动和运行,所以如果有一个单一的、易于理解的机制可以应用于所有方法,比如 @ensureConnected 装饰器,那就太好了.

在这里 fiddle :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());
}

}

关于javascript - 在 ES2015 中,如何确保所有方法都等待对象初始化?使用 ES7 装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com