3

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Duke Dougal
  • 24,359
  • 31
  • 91
  • 123
  • Add a callback parameter to your Client constructor, pass it a callback function, call that function after the server responds, and call the other client methods from the callback. – Michael Geary Mar 27 '16 at 01:20
  • FYI, decorators are not part of ES7 (ES2016). – Felix Kling Mar 27 '16 at 03:07
  • 1
    related: [Is it bad practice to have a constructor function return a Promise?](http://stackoverflow.com/q/24398699/1048572) - create your instances only once they are ready. – Bergi Mar 27 '16 at 06:30
  • If a coder does call the method before the connection is established, what should the method do other than throw an error? It's the best behavior as far as I can tell. – Herrington Darkholme Mar 27 '16 at 07:21
  • possible duplicate of [Are JavaScript ES6 Classes of any use with asynchronous code bases?](http://stackoverflow.com/q/37556058/1048572) – Bergi Jul 05 '16 at 15:33

2 Answers2

3

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.

Duke Dougal
  • 24,359
  • 31
  • 91
  • 123