Mastering the art of resolving a dynamic collection of promises with '$.all'

Imagine having 3 promises and passing them to $q.all. This results in a new promise that resolves when the 3 promises are resolved.

But what if I realize before the 3 promises resolve that I also want a 4th promise to be resolved? Can this be achieved?

I attempted something like this:

var promises = [promise1, promise2, promise3];
var allDone = $q.all(promises);
promises.push(promise4);

In the above scenario, allDone is resolved once the first 3 promises are resolved, but I want it to wait for the 4th promise as well.

Am I misunderstanding the concept of promises here? Is there a better approach for handling such situations?

Update: It seems that $q.all doesn't support the functionality I require. So, my question is, is there an alternative method to track the resolution of a changing set of promises?

Answer №1

You cannot simply add promises to the array afterwards and expect it to affect the previous .all() call. This is not how .all() functions. One alternative approach is:

var promises = [promise1, promise2, promise3];
var allDone = $q.all(promises);

$q.all([allDone, promise4]).then(function() {
    // All four promises are completed at this point
}); 

Alternatively, you can abandon the initial allDone promise and create a new .all() like so:

var promises = [promise1, promise2, promise3];
var allDone = $q.all(promises);

promises.push(promise4);
var all4Done = $q.all(promises);

Considering your feedback, here is another option. Say the final handler you want to call is in a function named allDoneNow(). You can try something like this:

var promises = [promise1, promise2, promise3];
var allDone = $q.all(promises);

allDone.then(function(results) {
    // If no new promises have been added
    if (promises.length === results.length) {
        // Call the final handler
        return allDoneNow(results);
    } else {
        // Wait for any new promises
        return $q.all(promises).then(allDoneNow);
    }
});

promises.push(promise4);

For a recursive approach to keep checking for more promises, you can use a function like this:

function waitAll(promiseArray) {
    return $q.all(promiseArray).then(function(results) {
        if (promiseArray.length <= results.length) {
            // All promises in the array are completed
            return results;
        } else {
            // There are new promises in the array, so wait for them
            return waitAll(promiseArray);
        }
    });
}

var promises = [promise1, promise2, promise3];
waitAll(promises).then(function(results) {
    // All promises in the array are done
});

promises.push(promise4);

Answer №2

Upon inspecting the source code of the $q all() function, one can see that it simply iterates through all promises using forEach() and then returns a new promise that resolves all the results thereafter.

Adding another promise to the array has no impact on the process, as the function already processes all promises and completes the task with the existing promises array.

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

Leveraging the power of mapState and mapMutations within a namespaced module

I'm having trouble accessing mutations and states after dividing my Vuex store into three modules. I've attempted various syntaxes, but none seem to be working for me. MapStates: This is how I have set up the mapStates, with 'vendor' a ...

Tips for avoiding deleting content within a span element when using contenteditable

I am working on an HTML 5 editor that utilizes the contenteditable tag. Inside this tag, I have a span. The issue arises when all text is removed as the span also gets removed. I want to prevent the removal of the span, how can I achieve this? Here is a s ...

The function is defined, but it cannot be set to null

Having trouble understanding this error message "Cannot set properties of null." I'm attempting to update the innerHTML with the output text from four functions that my button triggers. However, it seems to be stopping at the first function now even t ...

What are the benefits of using one state in React with useState compared to having multiple states?

Is it more beneficial to optimize and enhance code readability in React using Hooks and Functional components by utilizing a single setState hook or having multiple hooks per component? To further elaborate, let's consider the following: When workin ...

Utilizing the x-editable plugin in conjunction with meanjs yeoman-generated code: A Quick Guide

I'm a big fan of the x-editable plugin and have used it in the past for standalone Angular applications. However, I recently created my project using Yeoman meanjs generators and I can't seem to find the options for configuring editableOptions li ...

In Typescript, you can easily group a string into sections that consist of digits like 345-67, along with text containing a

I have a string that looks like this: "[111-11] text here with digits 111, [222-22-22]; 333-33 text here" and I am trying to parse it so that I can extract the code [111-11], [222-22-22], [333-33] along with their respective text descriptions. The challeng ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

Unable to verify the provided resource: Mailchimp

Welcome everyone to my first question posted on StackOverflow. I have tried my best to provide all the necessary details regarding the issue in order to seek assistance. If you require additional information, feel free to ask. To give a brief overview, I ...

Implementing an Ajax function for handling multiple button clicks

So, here's the situation - I've inherited a form with two buttons that inexplicably have the same name and id (seriously, don't ask me why, I didn't design this form haha). I'm attempting to utilize the Ajax .click function to trig ...

Incorporate pictures from the popup onto the main page

I have developed a basic PHP image editor script where users can select images from galleries and merge them together. However, I am facing an issue: The galleries open in a popup while the editor area is on the parent page. I am looking for a JavaScript ...

What is the process for pausing a video while it is still buffering and loading?

Is it possible to suspend a video when it is in an opening or preparing state? For example, if I open a video and then switch to another application using the smart hub feature, how can I suspend the video while it is in the process of opening or preparin ...

Customize the size of innerWidth and innerHeight in your THREEjs project

Is there a way to customize the size of the window where this function launches instead of it automatically calculating the height and width? I've attempted to modify this section of the code, but haven't had any success so far: renderer.setSiz ...

Warning: Update state in React-router-redux after redirection

I am currently developing an admin app for a project using react, redux, react-router, and react-router-redux. The version of react-router I am working with is v4.0.0, while react-router-redux is at v5.0.0-alpha.3 (installed with npm install react-router-r ...

The ability to rate the product in Livewire:Laravel is exclusively reserved for buyers

I have integrated the Livewire rating system into my Laravel e-commerce platform. Currently, all users can rate and comment on any product. However, I want to restrict this privilege to only buyers. ProductRatings.php class ProductRatings extends Componen ...

I'm encountering an error when trying to pass multiple parameters in an AJAX request

I am trying to pass three parameters to my ajax code. Here is the snippet of my code: $(document).ready(function () { SearchText(); }); function SearchText() { $("#txt712").autocomplete({ source: function (request, resp ...

Track WordPress Post Views on Click using AJAX

Is there a way to track the number of post views on my WordPress site using AJAX when a button is clicked? Currently, the view count only updates when the page is refreshed. I want to be able to trigger this function with an AJAX call. Here is the code I ...

Leverage PHP to dynamically populate a chart.js visualization with information sourced from an SQLite Database

I'm attempting to use chart.js to display data from an SQLite database using PHP, but I've been running into issues. Despite following multiple online tutorials, my graph remains empty or disappears altogether. This is my first time working with ...

Auth0 and Vue.js work together seamlessly to easily redirect users back to their previous page

I have integrated auth0 into my Vue.js application for handling logins. Within my AuthService, I manage all the auth0 operations. In the constructor, I instantiate a new auth0 object and set the default redirectUrl to the desired location: import auth0 f ...

The AJAX request was a success, but unfortunately there is no usable data available

After submitting the registration form, jQuery sends the data to register.php, which then responds with JSON data for jQuery to process. Everything seems to be functioning correctly as users are successfully registered. The network response tab shows that ...

When using Axios to GET from a local PHP file, it only retrieves the code instead of running

I've run into an issue accessing the API as it has CORS disabled, requiring me to make requests on the server side. Currently, I'm using React and Axios to send a GET request to a local php file that should trigger cURL execution. However, instea ...