In search of a resolution for the asynchronous problem using Javascript

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.

Answer №1

Not sure why the connect method is needed, but here's a solution:

export class WebsocketService {

  getSocket() {

    // This function will only return this.socket once it is available

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

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

        const token = localStorage.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;
  }
}

To use:

service.getSocket().then(socket => {
    // Use the socket
});

Or using async/await:

const socket = await service.getSocket();
// Use the socket

Answer №2

export class WebsocketManager {
    this.socket = io('http://localhost:3000', { query: { token: token }})
    public fetchSocket () {
        return new Promise((resolve) => {
           while (!this.socket.connected) {}
           resolve(this.socket)
        })
    }
}

then use:

manager.fetchSocket().then((socket) => {})

Receive the socket only when it's fully connected. It is assumed that the socket will be able to reconnect, but there may be errors if reconnection fails.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Populate an HTML5 arc with an image - Leveraging the power of HTML5 Canvas

I'm working with an HTML5 Canvas (JSFiddle) that currently displays circles created using the following function: function createball(x,y,r,color){ context.beginPath(); context.arc(x,y,r,0,Math.PI*2,true); context.fillStyle = color; c ...

What is the best way to determine if a radio button has been chosen, and proceed to the next radio button to display varied information?

The goal is to display the <div class="resp"> below each radio button when it is selected, with different content in each <div class="resp">. The previously selected <div class="resp"> should be hidden when a new radio button is chosen. O ...

NextJS rewrite retains URL search parameters

After a user clicks the button to access my website through email authentication, I need to verify if they have tokens. When they are redirected from Gmail to my page, there is a search parameter in the form of verification_token=**. If the user has alread ...

What is the best method to remove duplicate watches in AngularJS?

After creating a basic TODO app using AngularJS, I discovered some interesting features. https://i.sstatic.net/QHfdy.png The app allows me to manage my list of tasks, such as deleting, marking as completed, and adding new ones. A unique functionality is ...

An issue has occurred: the function cannot be applied to the intermediate value that is currently being processed

I am currently working on an Angular 5 CRUD application, utilizing Google Firebase services. I have been following a helpful video tutorial on YouTube (link here), but I encountered this error ngOnInit() { var x = this.employeeService.getData(); x.sna ...

`Can you teach me how to dynamically load HTML elements using input JSON data?`

What is the best way to iterate through an input array of objects? I currently have data for only 2 people included. However, there are more than 50 people's information in the input and I need to loop through all of them. Here is a sample code snip ...

Adjusting the height of the Iframe dynamically every 2 seconds

One issue I am facing is with the iframe height. When I load the iframe, it sets the height correctly and adjusts when content is loaded dynamically. However, if I reduce or delete content from the loaded page, the iframe height does not decrease (e.g., in ...

Issues arose with the presentation of information utilizing jQuery datatables, AJAX and JSON

I'm encountering an issue with displaying my data on the jQuery DataTable using AJAX. I am utilizing the library from datatables.net. Despite trying various JSON formats and experimenting with the 'columns' section by swapping 'title&ap ...

Tips for sending the parent object through a jQuery.ajax success function

I'm currently working on a function that includes child functions and objects: //API load function var apiDataLoader = function () { // Set default settings this.apiSeason = '7924'; this.apiMatchDay = '30'; th ...

Is it possible to conceal the # tag in the URL while using Angular routing?

In order to ensure proper routing functionality on the server host, we can set useHash = true in the app-routing.module.ts file like this: @NgModule({ imports: [RouterModule.forRoot(routes, { useHash: true })], exports: [RouterModule] }) Although thi ...

What are some effective ways to grasp Wordpress custom functions?

I have a custom theme and came across the line <?php sg_header_js() ?>. I assumed that checking Wordpress's functions folder might provide more insight. Upon examining functions>function.php, I found the following code: <?php //Textdomai ...

Having Difficulty Converting JavaScript Objects/JSON into PHP Arrays

This particular inquiry has no relation to the previously mentioned identical answer/question... In JavaScript, I am dealing with a substantial list of over 1,000 items displayed in this format... var plugins = [ { name: "Roundabout - Interac ...

Create new instances of Backbone Models using an existing Backbone Model as a template

Within my app, I am planning to include a configuration file called config.json as a Backbone Model. Here is an example of how it will be loaded: var Config = Backbone.Model.extend({ defaults: { base: '' }, url: 'config. ...

Is there a way to display only the specific child div within the parent div using JavaScript without affecting the others?

   **** Sorry for the lengthy title **** Today I encountered a problem that I would like to discuss with all of you. When I click on a "COMMENT" button, instead of triggering JavaScript code to display a CHILD.div inside the corresponding ...

Access and retrieve numerous variables from the data object sent back through an ajax request

When using jQuery to make an ajax call to an MVC controller, the goal is to return multiple variables from the controller. What is the best way to package this data in the controller and then extract it using jQuery? ...

Mastering ForEach Loops and SetTimeout in Angular 6: A Comprehensive Guide

While I understand this question may have been raised previously, none of the threads I have come across seem to address my specific issue. I currently have code written in angularjs that I am looking to transition to angular 6. My main goal is to impleme ...

Creating unique identifiers using node.js

function createUniqueID(count) { var found = false, characters = 'abcdefghijklmnopqrstuvwxyz1234567890', uniqueString = ''; while(!found) { for(var i = 0; i < count; i++) { uniqueString += ...

Vuejs application is not producing the anticipated outcome when an ordered list contains an unordered list

Is there a way to nest an unordered list within an ordered list in vue 2? I've attempted <template> <div class="p-14"> <ol class="numberlist"> <li>An numbered list</li> <li>Cont ...

jQuery - can you identify which specific object from the entire set this is?

I am curious if there is a simple method to identify which DOM object I have when it is also part of another set of objects. To illustrate, let's consider the following scenario: There are 5 div elements: <div id="1"></div> <div id="2 ...

Can you explain the purpose of this variable "guess = require('myModule1')('myModule2');" ?

While examining a code snippet, I stumbled upon this line and am unsure which instance it is referring to. var guess = require('myModule1')('myMmodule2') ...