Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...