Javascript,异步问题所需的解决方案

Wil*_*een 2 javascript asynchronous typescript es6-promise angular

目前正在使用Angular,socket.io和express创建应用程序.但是,我遇到了一个异步问题,我很难找到解决方案.这是代码:

  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 available

      return this.socket;

  }
Run Code Online (Sandbox Code Playgroud)

这个想法是,首先在应用程序的某个地方与websocket连接一次,因此io函数被调用一次:

    this.socket = io('http://localhost:3000', { query: { token: token } });
Run Code Online (Sandbox Code Playgroud)

然后在应用程序的其余部分中,this.socket应该传递属性.但是,this.socket应始终返回对象,如果不存在则应等待它.

实现还应该处理应用程序的其他部分,这些部分尝试调用getSocket并返回undefined.基本上,getSocket应该永远不会返回undefined它应该等待连接然后返回this.socket.

我尝试了一些承诺,但我似乎无法找到一个优雅的解决方案.

Hyy*_*her 6

我不知道为什么你需要这个connect方法,但这是一种方法

export class WebsocketService {

  getSocket() {

    // this function should only return this.socket when it is available

    if (!this.socket || (this.socket && this.socket.disconnected)) {

      this.socket = new Promise((resolve, reject) => {

        const token = sessionStorage.getItem('token');
        const s = io('http://localhost:3000', { query: { token: token } });

        s.on('connect', () => {
          console.log(socket.connected); // true
          resolve(s);
        });

        s.on('disconnect', () => {
          console.log(socket.disconnect); // true
          reject(s);
        });
      });
    }

    return this.socket;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,用法是:

service.getSocket().then(socket => {
    // Use the socket
});
Run Code Online (Sandbox Code Playgroud)

或者使用async/await:

const socket = await service.getSocket();
// Use the socket
Run Code Online (Sandbox Code Playgroud)