In ES2015 how can I ensure all methods wait for ob

2019-01-26 21:35发布

问题:

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.