Currently in the process of developing an application with Angular, socket.io, and express. Though, I am facing a challenge regarding asynchronous operations that I am struggling to resolve. Below is the snippet of code causing the issue:
export class WebsocketService {
this.socket;
public connect() {
const token = sessionStorage.getItem('token');
this.socket = io('http://localhost:3000', { query: { token: token } });
}
public getSocket () {
// This function should only return this.socket when it is ready
return this.socket;
}
The concept behind this is that initially, somewhere in the application there will be a connection established with the websocket by calling the io functions once:
this.socket = io('http://localhost:3000', { query: { token: token } });
Afterward, throughout the rest of the application, the this.socket
property needs to be used. The objective is for this.socket
to always return the object and wait for it if it's not available.
The implementation should also handle scenarios where other parts of the application attempt to call getSocket
and receive undefined. Essentially, getSocket should never provide undefined; it should await connection and then return this.socket
.
I've experimented with promises but haven't been able to discover an elegant solution yet.