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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…