Leverage socket.io within the resolve function to implement one-time event listeners

Previously, I placed one-time listeners inside the resolve. The code snippet below ensures that the page must receive a message of yes to resolve x, followed by "yes again" to resolve y, and so on:

app.config(['$stateProvider', function ($stateProvider) {
    $stateProvider
        .state('edit', {
            resolve: {
                x: ['$q', function ($q) {
                    var deferred = $q.defer();
                    $window.addEventListener("message", function (e) {
                        if (e.data === "yes") deferred.resolve(e.data)
                    }, { once: true };
                    return deferred.promise
                }],
                y: ... ...
                        if (e.data === "yes again") deferred.resolve(e.data)
                   ... ...
                    return deferred.promise
                }],
                z: ... ...
                    return deferred.promise

Now, I am considering using socket.io to handle these listeners; it listens for messages emitted by the server. If not within a resolve, receiving messages can be done by:

var socket = io.connect();
socket.on('message', function (message) {
   console.log(message)
})

I would like to assign one socket per page. Is there a way to incorporate this into multiple resolve functions to achieve similar functionality as the event listeners?

Answer №1

Event listeners and promises don't quite sync up due to their different natures - promises are one-time actions while event listeners can be triggered multiple times. This means that if you use a promise for an event, it will only respond to the initial trigger and ignore any subsequent events.

While it's conceivable to create a system where each event triggers a new promise in sequence, this process would require calling a function for each new promise generation, potentially leading to a messy workaround. It's generally more straightforward to utilize regular callbacks for individual event triggers and then introduce promises only when further asynchronous tasks need to be managed post-event.

Promises aren't designed to handle recurring events effectively. They excel at representing singular occurrences - like receiving confirmation once a file is successfully opened or getting a response from a specific http request via a resolved promise.

Answer №2

For achieving a one-time listener functionality, I have implemented the use of socket.once in my code. So far, there have been no errors and everything is working smoothly:

app.config(['$stateProvider', function ($stateProvider) {
    $stateProvider
        .state('edit', {
            resolve: {
                socket: [function () {
                    return io.connect();
                }],
                x: ['socket', '$q', function (socket, $q) {
                    var deferred = $q.defer();
                    socket.once("message", function (msg) {
                        if (msg.req === "yes") deferred.resolve(msg)
                    })
                    return deferred.promise
                }],
                y: ... ...
                        if (msg.req === "yes again") deferred.resolve(msg)
                   ... ...
                    return deferred.promise
                }],
                z: ... ...
                    return deferred.promise

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

The length of the HTTP response in Angular is not defined

Currently, I am utilizing Angular in conjunction with jQuery Mobile to develop multiple pages, but I have encountered an obstacle when using the $http service to connect to my JSON requests. While populating a few arrays with functions and successfully ret ...

Most effective method for removing the 'EDT' timezone abbreviation from a JavaScript date provided by toLocaleString() function

I'm just starting out with javascript and have a question about removing 'EDT' from the date returned when using toLocaleString. Any suggestions on how to do this easily? Thanks in advance! ...

Employ the function to write content onto a .js file

My experience with JS is fairly limited, mostly to basic animations. The current project I'm working on involves fading out the active div and fading in a new one. There are a total of 25 different divs that I need to transition between. However, I a ...

Using Node.js server along with MySQL database and socket.io technology for real-time

I need assistance in creating a Node.js server that integrates with MySQL and socket.io. Can someone please provide me with some sample code? Our database table consists of 20 columns, and every 30 seconds we receive new data through various operations s ...

Using JSON to store the image URLs instead of encoding them in base64

I am currently utilizing Three.js to store and retrieve objects in a database. The objects are being inserted as JSON format. However, the issue I am facing is that when using JSON.stringify or toJSON(), it converts the image url (textures) into base64 fo ...

Building on Angular 7, generate a fresh object by extracting specific values from an existing object

My object structure is as follows: const Obj = "Value1": { "value1value": "1" }, "Value2": { "value2value": "2" }, "Value3": { "value3value": "3" }, "BTest": { "1": "1", "2": "2" }, "Value4": { "value4value": "value4value" }, "ATes ...

Instructions for including a sentence in an array as a single element with the split method

I have a string and I want to turn it into an array by splitting it into individual elements. For example: let str = "add 2017-04-25 2 USD Jogurt" str.split(" "); ["add", "2017-04-25", "2", "USD", ...

Exploring the Depths of Scope Hierarchy in AngularJS

Upon inspecting the _proto__ property of an object I created, it is evident that it has been inherited from Object. https://i.stack.imgur.com/hcEhs.png Further exploration reveals that when a new object is created and inherits the obj object, the inherit ...

Working with JSON Objects in Java Script

I have a JSON object data in a JSP file and have passed this data to a JavaScript function through a hyperlink onclick method. The alert box displays properly, but the issue is that I want to extract the URLs in the JSON object and convert them into an arr ...

Tips for conducting performance analysis in React 16

In the React documentation, it is mentioned that react-addons-perf does not function with React 16 and suggests using Chrome's built-in tools for equivalent functionality. However, in my experience, I have not found this to be true. For example, let& ...

Retrieve a collection of elements that have been transferred from a Python file (using Django) to an HTML file, and then to JavaScript, all within the same webpage

Below is the Python code I have written: def index(request): body=list(Body.objects.all()) loads=list(Load.objects.all().order_by('length')) badLoads=[] goodLoads=[] for load in loads: if load.length>body[0].length ...

No search results found when using Vue.js searchbar filter

Today I delved into the world of VUEjs for the first time, experimenting with extracting data from a URL in JSON format. Initially, this process went smoothly, but my curiosity led me to attempt adding a search feature. I followed online tutorials, which u ...

Is it advisable to compress my API response in PHP?

At this stage, I find myself needing to generate extensive reports in order to gain a better understanding of the data at hand. To do so, I must retrieve one of my tables which contains around 50 parameters and 40,000 rows. While fetching the data via API ...

Next.js encountered an issue with the element type, as it expected either a string for built-in components or a class/function for composite components, but received undefined instead

Recently, while working with next js, I encountered an issue when trying to import a rich text editor into my project. Specifically, when attempting to integrate react-draft-wysiwyg, an error message was displayed: Error: Element type is invalid... (full e ...

Avoid constantly updating the rendering in React by utilizing callback functions

Is there a way to prevent Component B from rendering when I am only making changes in Component A? For example, if console.log("A") is associated with Component A and console.log("B") with Component B, I expect that updating text in Component A will only ...

Utilizing a React hook to render and map elements in a function

Can the hook return function be assigned to a render map in React? In this example, we have the socialAuthMethodsMap map with the onClick parameter. I tried to assign the signInWithApple function from the useFirebaseAuth hook, but it violates React's ...

What is causing my webpage to load items, flash, and then suddenly vanish?

I have written this code to fetch data from an API and display it on the screen. Interestingly, when I access localhost:3000, I can see all the information, but it disappears quickly afterwards. There are some warnings appearing in the console that say th ...

Utilizing the HTML method of jQuery on a jQuery element

Currently, I am attempting to modify the inner html of an element. When I utilize the following code: $('.best-photos-button')[0].innerHTML="Add More Photos"; the change is successful. However, if I try to use .html() instead of ".innerHTML" in ...

Upload of file successfully completed even though limit was set; input remains unchanged

I seem to be facing an issue where even after confirming with the ok in the window.alert message, the file name still appears next to Choose File. It seems like the file is still being uploaded to the input. How can I prevent this from happening? <inp ...

When attempting to declare a functional component in React utilizing styled-components in TypeScript, an error is encountered stating "No overload matches this call."

Playground https://codesandbox.io/s/typescript-type-checking-question-0b42t Sample Code type BadgeTypes = { success: string; secondary: string; alert: string; text: string; }; type Theme = { fonts?: object; borderRadius: string; primary?: o ...