Hello experts, can you advise on ensuring that asynchronous initialization in the service constructor is completed before calling other functions within 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 we can observe, the connection to the stomp-server is set up in the constructor. Subsequently, customers (components) of this service are encouraged to subscribe to topics they are interested in. It's logical that making a call to the subscribe function should only be done once the connection is fully established.
Additional Note: Furthermore, it's vital to ensure that the .connect method is invoked only once to avoid creating duplicate connections.