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

谁都会走 提交于 2019-11-28 05:36:10

问题


I have an ES2015 class that connects to a remote service.

The problem is that my code tries to access this class before its object has finished connecting to the remote server.

I want to ensure that methods don't just give an error if the object has not finished initializing.

I'll have alot of methods in my class that depend on the connection being up and running, so it would be good if there was a single, easy to understand mechanism that could be applied to all methods like an @ensureConnected 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)

I was imaging using ES7 decorators to implement a test to see if the connection is established but I can't see how to do so.


回答1:


I would not initiate the connection in the constructor. Constructors are more designed for initializing variables, etc., rather than program logic. I would instead call establishConnection yourself from your client code.

If you want to do this in the constructor, store the result in an instance variable, and then wait for it in doSomethingRemote, as in:

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());
    }

}



回答2:


In the end I tried a range of solutions including decorators and using the proxy object.

The solution I went for was to use ES7 async and await. After quite a bit of futzing around trying to understand how it works and the gotchas, managed to get it working.

So async and await were my most effective solution for ensuring objects had properly initialised.

I also took the advice of @torazaburo (see his answer elsewhere on this page) and ran the initialization method from a factory which first created and then initialized the object.



来源:https://stackoverflow.com/questions/36242757/in-es2015-how-can-i-ensure-all-methods-wait-for-object-to-initialize-with-es7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!