Suspend operation to delay for ajax call within a websocket

Looking for a solution regarding a WebSocket that updates a messaged list when receiving a message. Currently using a fetch request to retrieve data from the server in order to populate the messaged list. However, facing an issue as the code needs to pause until the fetch request is completed. Unfortunately, adding await is not an option here since the function is within a websocket that is not async. Any suggestions on how to tackle this problem?


        socket.on('receive_message', function(data) {
            let messaged_user_li = document.getElementById('messaged_user_li'+data['from_user']);
            console.log('messaged_user_li: '+messaged_user_li)
            if (messaged_user_li == null) {
                console.log('if fired')
                //THIS is the fetch I want to pause the function until complete. Note that the await here does not work since the funciton isn't async.
                await fetch('/get_messaged_user/'+from_user).then((response) => {
                    response.json().then((data2) => {
                        loadMessagedUser(data2[0].id, data2[0].avatar, data2[0].username, data2[0].last_seen);
                    });
                });
                messaged_user_li = document.getElementById('messaged_user_li'+data['from_user']);
            }
            console.log('messaged_user_li: '+messaged_user_li)
            let message_user = document.getElementById('message_user'+data['from_user']);

            let message_target = document.getElementById("message_target"+data['from_user']);
            if (messaged_user_li.classList.contains('active') == false) {
                messaged_user_li.classList.add('flash-message');
            }
            if (message_user != null) {
                data = `
            <li class="clearfix">
                <div class="message-data text-right">
                    <span class="message-data-time">just now</span>
                </div>
                <div class="message other-message float-right">`+data['message']+`</div>
            </li>`;
            message_target.innerHTML += data;
            //Move scroller to bottom when message received
            myDiv = message_user.querySelector(".chat-history");
            myDiv.scrollTop = myDiv.scrollHeight;
        }
    });
    

Answer №1

It's possible to include an asynchronous function within the socket.on method.

socket.on('receive_message', async function(data) {

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

Enhance efficiency of repetitive tasks involving accessing the Mongo database

Currently, I am developing a chat bot using MeteorJS/NodeJS, which engages with approximately 2,000 active users on a daily basis. Tracking the number of individuals who interact with the bot each day is made possible by storing their activity information ...

The issue arises when attempting to call a method from the same service within jsPDF in an Angular environment

Below you will find my Angular project's pdfService. I am facing an issue where calling the this.formatter() method inside myPDF is not functioning properly. export class pdfService { formatter(value: number): string { return new Intl.N ...

Angular's jQuery timepicker allows users to easily select a

Transitioning from jQuery to Angular, we previously utilized the for selecting times due to Firefox not supporting HTML5 input time. While searching for a similar timepicker plugin for Angular to maintain consistency with our past data and styles, I came ...

What causes the result of UNDEFINED when accessing an ENVIRONMENT VARIABLE in a REACT application?

Unfortunately, I've hit a roadblock with this seemingly simple question and can't seem to find the answer. I'm having trouble accessing environment variables in a specific file. I am using create-react-app (^16.11.0) The .env file is loca ...

Transform the text column into JSON format

We currently have a resource bundle/properties formatted as follows: [tag1] server1 server2 [tag2] server3 server4 [tag3] server5 server6 [No Software Installed] server7 [tag2] server8 [tag5] server9 [tag1] server10 server11 [tag3] server12 server13 serve ...

waiting for udp response in node.js using express

Currently, I am diving into the world of node.js programming and have encountered a challenge. While working with express, I came across an issue. When a POST request is made, it triggers a radius authentication process over UDP using the dgram module. Ho ...

Anguar server encountered a startup issue and failed to initialize

My server.js file looks like this: var express = require('express'), api = require('./api'), app = express(); app .use(express.static('./public')) .use('./api', api) .get('*', ...

How to stop a div from shifting downwards with CSS

Within my Web Application, I have implemented HTML code that displays different texts above input fields based on certain conditions. However, the issue I am facing is that the input fields are being shifted down by the text. I want the input fields to al ...

Request successful but receiving no response text and content length is zero

let req = new XMLHttpRequest(); req.addEventListener('load', function (data) { console.log(data) }, false); req.open("get", "/bar.txt", true); req.send(); Feeling a bit perplexed at the moment, I can't seem to figure out what's going ...

Launching Angular Application on GitHub Pages

I am encountering an issue with my GitHub Pages website that is connected to a custom domain. My domain is hosting a web application created with Angular, but I am having trouble loading the .js and .css files when I visit the site. In the DevTools/Networ ...

Unveiling the secrets of interacting with localstorage in react.js

I'm currently facing an issue with a component that retrieves data from an array stored in local storage. Although the initial data is fetched when the page loads, I am unsure how to update it when changes are made in local storage. import React, {Co ...

Information failed to load into the datatable

i've implemented this code snippet to utilize ajax for loading data into a datatable. However, I'm encountering an issue where the data is not being loaded into the database. $('#new_table').DataTable({ "processing": true, "ser ...

Can ng-packagr create scripts that are compatible with running in a web browser like regular JavaScript?

Is it feasible to utilize ng-packagr to compile a library into a single script file that can be executed on a web browser by importing it as <script src="bundle.js"></script>? For instance, if I have a main.ts file that contains cons ...

Best practices for making an AJAX call to fetch information from a database

I have a database containing a single table. The table includes columns for Company and Time, among others, with Company and Time being crucial. Users can make appointments by filling out a form. Within the form, there are 2 <select> elements - one ...

What is the best way to utilize JSONP to display an entire HTML code with an alert?

When I attempt to use cross-domain ajax to retrieve the entire HTML page code, I keep receiving a failed message. The console log shows: "Uncaught SyntaxError: Unexpected token <" Below is my AJAX function: function fetchData(){ var url = documen ...

Nuxt 3.11 - Best Practices for Integrating the `github/relative-time-element` Dependency

I'm encountering some difficulties while attempting to integrate github/relative-time-element with Nuxt 3.11.2 and Nitro 2.9.6. This is my current progress: I added the library through the command: $ npm install @github/time-elements. I adjusted nux ...

Send the loop index as a parameter to a function within the onclick attribute of an HTML <input> element using vue.js

My goal was to develop a basic to-do list using vue.js to familiarize myself with it. Now, I've successfully added a remove button next to each item. To achieve this, I included a remove() function in JavaScript with a id parameter, which corresponds ...

Rendering the page using ReactDOM.render

Just started with ReactJS, I'm struggling to figure out why my page isn't displaying anything - <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> ...

Whenever I work with NPM, node.js, and discord.js, I consistently encounter the error message stating "TypeError: Cannot read property 'setPresence' of null."

I'm developing a Discord bot with NPM and discord.js, but I keep encountering an error that says "TypeError: Cannot read property 'setPresence' of null". Here is my bot code: const Discord = require('discord.js'); const { prefix, ...

Steps to Incorporate jQuery Function in a Partial View Inside a Modal

My jquery button click method is functioning correctly in views outside of modals, but the uploadbtn button click method does not work when a partial view is loaded in the modals. <script src="~/lib/jquery/dist/jquery.min.js"></script> ...