Ensuring promise resolutions in a chain using Angular JavaScript before delivering a final result

I have a scenario in Angular where I am using a chain of promises and I want to ensure that a value is returned at the end of the chain:

this.calculateeventsattended = function(username) {
   var Attendees = Parse.Object.extend("Attendees");
   var User = Parse.Object.extend("User");
   var count_pres = 0
   query1 = new Parse.Query(Attendees);
   query1.equalTo("user_id",username);
   query1.equalTo("presence",true)        

   var promise = query1.count(function(count){
       count_pres = count
   }).then(function(){
       query2 = new Parse.Query(User);
       query2.equalTo("username",username);
       query2.first().then(function(object){
           alert("parse" + count_pres)
           object.set("events_attended",count_pres)
           object.save()
       })
   })
$q.all(promise)
return count_pres
}

However, I am facing issues where the 'promise' chain is not resolved before the return statement is executed. This means that count_pres is being returned before $q.all(promise) has finished execution. Any suggestions on how to address this?

Answer №1

It seems doubtful that this approach will be successful. The comparison between chaining promises and writing asynchronous promises is an interesting one.

function chainedPromises() {
    return $q(function(resolve) {
        query
            .firstPromise()
            .then(function(firstResult) {
                return query.secondPromise(firstResult.something);
            })
            .then(function(secondResult) {
                return query.thirdPromise(secondResult.something);
            })
            .then(function(thirdResult) {
                return query.fourthPromise(thirdResult.something);
            })
            .then(function(fourthResult) {
                resolve(fourthResult);
            });
    });
}

function asyncPromises() {
    var promises = [];

    promises.push(query.firstPromise());
    promises.push(query.secondPromise());
    promises.push(query.thirdPromise());
    promises.push(query.fourthPromise());

    return $q.all(promises);
}

chainedPromises()
    .then(function(fourthResult) {
        doSomethingWith(fourthResult);
    });

asyncPromises()
    .then(function(results) {
       doSomethingWith(results); 
    });

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

Wait until the link is clicked before showing the list element

Is there a way to prevent the display of list element id="two" in the code below until link "#two" has been clicked, removing element id="one"? I am looking for a CSS or JS solution that completely hides the list element rather than just hiding it from vie ...

When trying to access document.cookie, an empty string is returned despite the presence of cookies listed in developer tools, and the httpOnly flag is set

There are times when I encounter an empty string while trying to access document.cookie on the login page, despite the following conditions being met: The cookies are visible in the Chrome and Firefox developer tools, The httpOnly flag of the cookie I&ap ...

Following different ng-repeat loops in AngularJS, keeping control of the inner $index variable can be

My goal is to display a nested data structure with a continuous inner $index. Here's an example of what I want: Category Name 1 1. Foo 2. Bar 3. Fez Category Name 2 4. Qux 5. Baz But currently, I am getting this result: Catego ...

Passing data from the controller to the $resource object in Angular with the MEAN stack

After several attempts to troubleshoot my issue with passing parameters to the Express server, it turns out the problem lies on the Angular side. When I manually inserted the id in the flConstruct.js function, the query worked correctly. It appears that ...

What is the method to reach a named parameter within a function?

Currently, I am building a RESTful web service using Node JS in combination with Backbone JS. Within this service, there is a specific REST method called GET /users/id/:id, where :id represents the user's identification number. The purpose of this met ...

When using React, the componentDidUpdate() method may have trouble locating DOM objects that were originally rendered by the render() method

Update: I made some changes to the code by adding and utilizing refs instead of document.getElementById. Unfortunately, this did not solve the issue. Update 2: After experimenting with mutationObserver, it became apparent that componentDidUpdate() starts ...

What steps should be followed to construct a window identical to the one depicted in the attached image using HTML and CSS?

Check out this link to see the window style I'm trying to recreate using HTML, CSS, and Javascript. No Jquery needed. Thank you in advance. ...

Is it possible to change the background color using jQuery?

Can you assist me with this: I have a website and I am looking to modify the bg-coler when hovering over the menu (similar to how it works on the rhcp-website). I attempted using jquery for this, but unfortunately, it did not yield the desired result.. ( ...

I'm looking for a creative JavaScript prototype example that can help illustrate the concept of prototypes. Can someone share an interesting sample with me

I've been trying to wrap my head around prototypes, but I just can't seem to grasp their purpose and function. Is there anyone who can provide a straightforward example (such as a collegeStudent object) that will clarify the fundamentals of proto ...

Trustpilot Authentication Error: Grant_type Not Recognized

I am attempting to utilize the Trustpilot API for sending email review invitations. Before making the call, I need to obtain an access token as per Trustpilot's documentation. However, when implementing the function below, I am encountering an error i ...

Comparison of Transform plugin and Syntax plugin within Babel

I am interested in incorporating Class properties into my webpack configuration. While following a tutorial on the website (www.survivejs.com), I came across two plugins being added to the .babelrc file: babel-plugin-syntax-class-properties and babel-plugi ...

Are there any factors within a local network or desktop environment that may impact the execution of JScript?

Something strange is happening with the JavaScript on my project. It works perfectly fine, except when accessed from computers at a specific company. Even more puzzling is that the JavaScript only fails about half of the time when accessed from that compan ...

Changing states in next.js is not accomplished by using setState

Struggling to update the page number using setCurrentPage(page) - clicking the button doesn't trigger any state change. Tried various methods without success. Manually modified the number in useState(1) and confirmed that the page did switch. import ...

ControlsContainer - jQuery object for Flexslider

I recently tried to implement a flexslider with controls in a separate div using the controlsContainer option provided by flexslider. The setup consists of a left column containing the slider code (".flexslider-small"), a right column with text, and the c ...

Obtaining a 16-bit integer from the response of an LWIP server

On the server side, I have implemented a loop that takes a 16-bit integer ranging from 0 to 639 and splits it into two 8-bit characters to populate a buffer of 1280 Bytes. The buffer is then sent via TCP-IP to the client. .c unsigned int data2[1000]; ch ...

When attempting to call an XML node with JavaScript in an HTML file within Dreamweaver, the functionality works as expected. However, upon testing the same code on a server

As a beginner in Javascript, I am attempting to use document.write to display some XML data in an HTML format. Below is the code that I have been working on: <script> function loadXMLDoc() { if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest( ...

Any suggestions on how to repair this Node.js login interface?

Currently grappling with setting up a Node.js application with a MySQL database to create a basic login functionality. Encountering an issue: Cannot POST /login <body class="hero-image"> <div id="container"> <div ...

Encountered an error message stating 'Unexpected Token <' while attempting to launch the node server

After adapting react-server-example (https://github.com/mhart/react-server-example), I encountered an issue with using JSX in my project. Despite making various changes like switching from Browserify to Webpack and installing babel-preset-react, I am still ...

NodeJS: The functionality of my node files relies on the variables defined in another file

For my nodejs app, I have created a script called app.js that serves as the entry point. This script initializes both the expressjs app and the http server. To clarify: The modules mentioned are not npm modules; they are custom files that I have written m ...

The function is failing to return a false value

I have encountered a problem with my code - it works fine in Chrome but not in IE or Firefox. I've tried using return false; and event.preventDefault() but they don't seem to be effective in Firefox. The issue arises when the button grabs informa ...