How can I ensure that async initialization in the

2019-06-13 01:35发布

Experts, please tell me how to make sure that asynchronous initialization in the service constructor is complete when calling other functions in the class?

  constructor() {
    var sock = new SockJS(this._chatUrl);
    this.stompClient = Stomp.over(sock);
    this.stompClient.connect({}, function () {
    });
  }

  public subscribe(topicName: string, messageReceived) {
    this.stompClient.subscribe('/topic/' + topicName, function (message) {
      messageReceived(message);
    })
  }

  public sendMessage(msgDestId: string, message) {
    this.stompClient.send("/app/" + msgDestId, {}, JSON.stringify(message));
  }

As you can see, the connection to the stomp-server is established in the constructor. After that, customers (components) of this service are invited to subscribe to topics of interest. Naturally, the call to the subscribe function does not make sense until the connection is fully established.

Update: It is also important to keep .connect method called only once. Otherwise it creates two connections.

1条回答
仙女界的扛把子
2楼-- · 2019-06-13 02:10

Make every interaction with the stomp client through a promise, e.g.:

constructor() {
    ...
    this.stomp = new Promise(resolve => {
        stompClient.connect({}, () => resolve(stompClient));
    });
}

subscribe(...) {
    this.stomp.then(stompClient => stompClient.subscribe(...));
}
查看更多
登录 后发表回答