Working with AngularJS's $q promise and socket.io

I am interested in creating an angularJS promise that can work seamlessly with socket.io. Currently, I have a callback function set up to handle the response like this:

function request(event, data, callback) {
    socket.emit(event, data);
    socket.on(event, function(d) {
        socket.off(event);
        callback(d);
    });
}

As a result, my code looks something like this:

request('myEvent', 'Hello World !', function(data) {
    ...
});

I am curious if it's possible to implement a promise instead (using the $q service from angular) like so:

request('myEvent', 'Hello World !').then(function(data) {

});

Any insights on how to achieve this would be greatly appreciated! Thank you!

Answer №1

If you're looking to implement a similar solution, consider the following:

function sendRequest(eventType, payload) {
    let promise = new Promise((resolve, reject) => {
        socket.emit(eventType, payload);
        socket.on(eventType, (response) => {
            socket.off(eventType);
            resolve(response);
        });
    });
    
    return promise;
}

Then, you can make use of it like this:

sendRequest('customEvent', 'Hello Universe !').then((responseData) => {

});

Answer №2

const sendRequest = (event, payload) => {
  return new Promise((resolve, reject) => {
    socket.emit(event, payload);
      socket.on(event, (response) => {
        socket.off(event);
          resolve(response);
      });
  });
}

Answer №3

So, when it comes to promises, they can only fulfill or reject once. If the event happens more than once, does it matter to you?

If you're fine with the event firing only once, then go ahead and promise it.

function sendRequest(event, data, callback) {
    socket.emit(event, data);
    socket.on(event, function(responseData) {
        socket.off(event);
        callback(responseData);
    });
}

The updated version is as follows:

function sendPromise(event, data) {
    return $q(function(resolve, reject) {
       socket.emit(event, data);
       socket.on(event, function(responseData) {
           socket.off(event);
           resolve(responseData)
       });
    });
}

Here's how you can use it:

sendPromise('event', data).then(....)

Answer №4

Encountered an issue where wrapping socket.on(event) in a function and calling it multiple times resulted in opening multiple instances. This caused the specific socket event to be called multiple times by the backend. Resolved this by using $rootScope.$on, which ensures only one instance is created.

this.search = (query) => {

    var deferred = $q.defer();

    socket.emit('search', {query: query}) // send data to backend

    $rootScope.$on('search', function(event,data){

        deferred.resolve(data);

    });

    return deferred.promise;
}

//get data back from backend
socket.on('search',(data) => {

    $rootScope.$emit('search',data);

}); 

The above code snippet is enclosed within an Angularjs service. To retrieve data from socket.on('search'), you can utilize the following:

SocketioService.search('Some query').then( (data) => {
  //do something with the data from the backend
})

This solution may not be optimal, but it effectively resolves the issue :)

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

Let's discuss how to include the scrollTop option

I am new to coding and I need help adding a scrollTop margin of +100px to my code. The page already has some top margin but I can't seem to locate it. I'm also having trouble finding where the margin-top is being set in the JavaScript file. /*** ...

When reference variables are utilized before being parsed, what happens?

I'm a beginner learning Angular and have a question regarding the use of reference variables. Here is an example code snippet: <div class="bg-info text-white p-2"> Selected Product: {{product.value || '(None)'}} </div> <di ...

Unable to see the array values in jquery autocomplete

Hey there, I'm currently using jQuery autocomplete with CodeIgniter. My result array is fetched from the database and I am sending it back as JSON-encoded data. However, I am facing an issue where the values in the search results are not being display ...

Retrieve the string data from a .txt document

I am facing an issue with my script that retrieves a value from a .txt file. It works perfectly fine when the value is a number, but when trying to fetch text from another .txt file, I encounter the "NaN" error indicating it's not a number. How can I ...

Troubleshooting Deployd Launch Failure Due to MongoDB

Having attempted to troubleshoot this issue based on past discussions, I am still facing difficulties. Currently, I am following the Apress Pro Angular book and today, I am using a different machine with all necessary content. However, Deployd is encounter ...

Webpack is mistakenly duplicating module loading

I've been working on my angular.js application using webpack for building, and came across an interesting issue. Take a look at this simple example: app.js var angular = require('exports?window.angular!angular'), angularMoment = requir ...

How to Access Information from a Node.js Server Using Socket Connections?

I am facing an issue with fetching data from my Node server. I have searched through multiple online resources, but so far, I haven't come across a solution to my problem. Here is the code for my Node server: var socket = require('socket.io&apo ...

Creating a unique array of non-repeating numbers in ES6:

Looking to create an array of unique random numbers in ES6 without any repeats. Currently, my function is generating an array of random numbers that are repeating: winArray = [...Array(6)].map(() => Math.floor(Math.random() * 53)); Here is a non-ES6 ...

Using React.js to compute dates based on user-inputted dates

Today was dedicated to tackling the coding challenge of creating a function. I'm currently working on a react app using the PERN stack. The form I'm working on includes multiple date inputs, with two date columns and a total days column. My goal ...

Exploring the functionality of Protractor testing in combination with Angular 2, focusing

I am currently developing an Angular 2 application and I require some information regarding unit testing with Protractor. Previously, in Angular 1, we were able to check for things like: element(by.css('[ng-click="myFunction()"]')) in our test ...

"Converting a standard grammar with recursion and alternations into a regular expression: A step-by-step

A grammar is considered regular if it follows either a right-linear or left-linear pattern. According to this tutorial, this type of grammar possesses a unique property: Regular grammars have a special characteristic: through the substitution of every no ...

Using third-party libraries like jQuery, CSS, and JavaScript in your React project by directly importing them into the index.html file can be a more efficient approach compared

When working with React, is it advisable to import external JavaScript, jQuery, and CSS files into the index.html file in the public folder? Are there any potential performance implications associated with this practice? I have utilized some jQuery functi ...

While creating a React app, Docker becomes stuck due to a hangup when checking the core-js dependency

I've hit a roadblock in the build process. I'm working on an M1 Mac Mini and have attempted to build in both arm64 and x86_64 terminals, but the outcome is consistently the same. npm info lifecycle @babel/<a href="/cdn-cgi/l/email-protection" ...

AngularJS | Using ngAnimate to Display Form Validation Errors

My form errors are currently being displayed successfully using CSS and conditional classes, but I recently discovered ng-message and ng-animate. Would it be possible to use ng-message to contain the error messages? Also, I have been unable to find any tu ...

What is the process for configuring the Authorization Header in ng2-signalr?

I am currently utilizing the library ng2-signalr within my ionic 2 project. I am facing an issue regarding setting the authorization header, as I have been unable to find any examples on how to do so. Below is my code snippet for establishing a connection ...

What is the best way to eliminate the input range in a React date range picker?

Here is an image illustrating a date range picker: https://i.stack.imgur.com/pwKaI.png I am looking to remove the labels for days before today and starting from today in the date range picker. How can I achieve this? Below is my code snippet: class Better ...

Exploring the realm of styling with React JS

Currently, I am facing an issue while working with material-ui for my web design. Here is the code snippet that I am using: const useStyles = makeStyles((theme) => ({ card: { marginTop: theme.spacing(10), direction:"column", alig ...

What steps should I take to incorporate Bootstrap's JavaScript into Vue (Gridsome)?

Check out my website: The site is built with Gridsome, a static site generator for Vue. If you navigate to the mobile version and try to open the Bootstrap Hamburger menu, it doesn't work as expected. I've followed the instructions in Gridsome ...

Connecting two fields with a line on click in AngularJS

In the top section, there are 10 fields and in the bottom section, there are another 10 fields. I want to be able to connect two fields with a line when they are clicked (one from the top section and one from the bottom section). This connection should app ...

Enable automatic real-time updates of an Angular view based on changes in the length of

I am curious about how Angular detects changes in a MongoDB collection. I have a variable keeping track of the number of items in my database, and I want the front end to automatically update the display whenever a new item is added from the front end. Is ...