Checking two promises in AngularJS to ensure they have both returned successfully

I am faced with a scenario where I need to execute actions as each promise returns individually, and perform another action once both promises have returned successfully.

promise1.then(function() { // do something })

promise2.then(function() { // do something })

$q.all([promise1, promise2]).then(function () { 
   var dependsOnBoth = promise1.x && promise2.x;
})

I am curious if duplicating the promises results in duplicate calls, and if there is a more efficient way to ensure that both promises have completed. Thank you!

Answer №1

By invoking then on each promise, you are essentially calling it twice - once for each promise individually, and once in the $q.all function that encompasses both promises. This results in each promise being called twice in total.

Solution one:
To avoid this redundancy, it is recommended to refrain from calling then on each promise. Instead, only utilize it within the $q.all function.

var promise1 = function(){
 var promise1defered = $q.defer();

    // Resolve promise1 here.
    promise1defered.resolve();

   return promise1defered.promise;
}

var promise2 = function(){
var promise2defered = $q.defer();

    // Resolve promise2 here.
    promise2defered.resolve();

    return promise2defered.promise;
}

$q.all([promise1, promise2]).then(function () { 
  // Both promises are resolved at this point.
})

Solution two:
An alternative approach is to chain promises instead of using $q.all.

var promise2 = promise1.then(function(){  

     // Action to be taken after promise1 is completed
    // Resolve promise2 here
]);

promise2.then(function(){  

    // Action to be taken after promise 2 is completed
    // Both promise 1 and promise 2 are completed at this stage.

});

Answer №2

The sequence of function execution within a promise is determined by the order in which they are added. This means that each individual function specified with then() will be executed before the all.then() function. It's important to note that each then() function will only be executed once, providing a reliable way to manage the sequence of operations.

An alternative approach is to consolidate all post-processing operations within the all route, as it ensures they will be performed after the completion of both individual functions.

Lastly, remember to include error callbacks to handle any potential exceptions that may occur during the promise execution.

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

Modifying the data of an HTML form using Javascript, encrypting the information, and transferring it to PHP

I am new to PHP and have a simple code management question. I would like to create an input box in HTML where someone can enter their name, and with the use of Javascript, generate a link with an encoded version of the name preceded by a website string. Wh ...

Obtaining solely the words found within HTML documents

In my Python 2.7 project, I have a folder containing multiple HTML pages that I need to extract only words from. My current process involves opening the HTML file, using the Beautiful Soup library to extract text, and then writing it to a new file. However ...

Set panning value back to default in Ionic

I need assistance with resetting the panning value. Essentially, I would like the panning value to return to 0 when it reaches -130. Below is my code snippet: swipeEvent($e) { if ($e.deltaX <= -130) { document.getElementById("button").click(); ...

How can I ensure that a group of jQuery sliders are always locked to a combined total of 100?

Seeking assistance with implementing NoUiSlider on multiple pages with varying numbers of sliders (). Attempting to set up the sliders with a total value constraint of 100, enabling adjustment of one slider to affect the values of others inversely, yet un ...

Enabling or disabling select input based on the selected option in a previous select dropdown

My goal here is to customize a select input with 3 options: Sale, Rent, Wanted. Based on the selection, I want to display one of three other select inputs. For example, if "Sale" is chosen, show the property sale input and hide the others. However, when su ...

Netlify encountered an error with mixed content, indicating that the page was successfully loaded over HTTPS, but it attempted to request an insecure HTTP

hey everyone, Recently, I deployed my vue-cli website project on Netlify. However, upon opening the website, I encountered the following error message: Mixed Content: The page at 'https://xxxx.netlify.app/' was loaded over HTTPS, but requested a ...

What is the better choice in NodeJS: using "return cb(..)" or first calling cb(..) and then returning?

Forgive me if this sounds like a silly question, but I'm curious about the implications of something: Whenever I encounter an error or need to complete a function flow, I follow certain instructions such as: if(err) { cb(err); // or for exampl ...

Creating a Dynamic Bar in Your Shiny Application: A Step-by-Step Guide

Currently, I am developing a unique crowd funding shiny app to monitor donation amounts. Is there a method available that allows for the creation of a reactive bar in Shiny? Alternatively, is it feasible to achieve this using html, css, and javascript? He ...

Exploring various textures applied to a sphere in Three.js

Is there a way to load multiple textures onto a sphere? Can we divide a sphere into n sections in Three.js, texture them individually, and then combine them to render the sphere as a whole? Instead of loading the entire texture onto the sphere at once, I ...

What is the best way to print a canvas element once it has been modified?

My goal is to include a "Print Content" button on a webpage that will print a canvas element displaying workout metrics. However, the canvas content, which consists of a visual graph of workout data, changes based on the selected workout (bench, squat, etc ...

Retrieve information from an external source and subsequently make alterations to it

If a certain external site returns a string like "cost is 10$", is it possible for me to display it as "price:10$" on my own website using only Javascript? The external site could be something like Facebook.com. My website, of course, belongs to me. Hello ...

transferring information from browser storage to the server

On my web app, there is a feature that saves data to local storage and converts it to a JSON object. I'm interested in passing this local storage data to my server using AJAX, so that other clients of the web app can access it. Is there a way to accom ...

How can I extract the value from the object returned by an AJAX call?

HTML file <div class="container"> <table id="headerTable" class="table table-bordered"> <thead> <tr> <th colspan="2">Header</th> </tr> </thead> <tbody> <c:forEach item ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

Unexpected twist observed when custom curve is applied to Threejs TubeGeometry

After creating a custom curve applied to TubeGeometry, I noticed an interesting behavior. The curve's vertices on the X axis change based on mouse movement, while the Z axis follows a simple sin curve affected by time. The code snippet below demonstra ...

Add AngularJS to an AJAX call when the user clicks on it

I'm currently exploring the SoundCloud API and looking to implement a feature where users can add a song to the page by clicking on it from the search results. I've decided to utilize Plangular, which you can find more information about here. How ...

Guide to creating a search-enabled dropdown menu

Recently, I created a dropdown menu using Bootstrap. The code I used can be found here: http://getbootstrap.com/docs/4.0/components/dropdowns/ <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownM ...

Activate the audit command for the npm enterprise registry

I'd like to know how to activate the npm audit command in my npm enterprise registry. Whenever I attempt to run the npm audit command, I encounter the following error: { "error": { "code": "ENOAUDIT", "summary": "Your configured registry ( ...

Issue: React child components cannot be objects (received: object with keys)

Hey everyone, I could really use some help figuring out what I'm doing wrong. Here is the error message I'm receiving: Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a ...

Discovering Unnecessary CSS & JS Code

Currently, I am tackling a freelance project focused on upgrading a website. The client is requesting specific features from their old site be replicated on the new one. However, the challenge lies in the fact that the old site's CSS and JS are consol ...