Angular q.all: comparing immediate and delayed responses

Seeking advice on methodology: I currently utilize $q.all to handle multiple promises in a single return, processing all results as one request.

For instance:

$q.all([promise1(),promise2(),promise3(),promise(4),promise5()])..then(function(response){ ...}

However, I have observed that different promises are often returned at varying time frames. These promises are all http calls to third party sites. When one promise is delayed by 8 or 14 seconds, the final results of all promises are similarly delayed. A case of the 'slowest link' syndrome.

Is there an alternative method to simultaneously call all promises while allowing results to be processed and displayed to the user as they arrive, rather than waiting for all promises to return before processing them collectively?

Answer №1

If you prefer to use them separately as suggested in the feedback, that is an option. However, for those who are interested in calling all of them simultaneously and handling them within one promise, the notify-callback of the promise can be utilized. I've developed an extension for $q that leverages the notify() function to resolve the promises collectively:

app.run(function($q){
    $q.each = function(promises){
        var deferred = $q.defer();

        promises.forEach(function(promise){
            promise.then(function(data){
                deferred.notify(data);
            });
        });
        return deferred.promise;
    };
});

Although this implementation is simplistic and lacks error handling, it provides a basic understanding of the process involved.

To use this extension, simply follow this structure:

var promises = [promise1(), promise2(), promise3(), promise(4), promise5()];

$q.each(promises).then(null, null, function(data){
    console.log(data);  // This function is executed upon resolution of each promise.
});

For a demonstration of this concept in action, you can view the following Plunker

Answer №2

It is important to remember that functions like then() or $q.all() do not control the order in which promises are executed; they simply define when you want a response. Even though myPromise.then(doSomething) may suggest otherwise, the promises begin running as soon as they are created.

Additionally, $q.all does not combine promises in the traditional sense; instead, it creates a new promise that resolves or rejects based on the outcomes of the original promises. This means a promise is not restricted to a single handler...

promise1.then(function () {
    //logic that only depends on promise1 and does not require the others
});
$q.all(promise1, promise2, ...).then(function () {
    //logic that can only be executed once all promises are completed
});

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

Setting the default value for drop-down menus in jqGrid form editing

I have a data object with 3 attributes: ID Abbreviation Description In my jqGrid setup, I've configured the grid to display the Abbreviation. During editing (using the Form Edit feature), I populate the dropdown list with ID/Description pairs usin ...

What sets Angular and Meteor apart from each other?

Can you explain the contrast between Angular and Meteor? While it is true that both adhere to the model-view-viewmodel architecture, what sets these two frameworks apart from each other? ...

Tips for adding a "Select All" feature to a dropdown list?

Currently, I have a dropdown list with a filter for IN and OUT values. The functionality is working as expected: <select class="form-select" style="max-width: 100px" [ngModel]="selectedBrand" (ngModelChange)="onChangeT ...

An error of type 'TypeError' has occurred, where it is unable to access the property 'render' of an undefined element in

I'm using a function in my controller to render the "result" in my "home-page" view, which is calling my model to execute the query. exports.searchNoms = (req, res) => { getDatabaseModel.searchNoms(req).then(function(result) { console.l ...

Tips for targeting an element for focus following a re-render in ReactJS

Within my web application, when a user hits the enter key, they are able to save the current record. A message confirming that the "record has been successfully saved" is then displayed. However, I have noticed that the blinking cursor in one of the input ...

What could be the reason for v-model not functioning properly?

Embarking on my Vue.js coding journey, I am currently following a straightforward online tutorial. Utilizing the vue-cli, I kickstarted my application and crafted a basic component named Test.vue. Within this component lies a simplistic input control conne ...

Encountered an issue while installing the "sharp" module on MAC M1

When I run npm run dev (gatsby develop) on my MacBook Pro M1 chip, it exits with the error message: Error: Something went wrong installing the "sharp" module However, when I run npm run dev on a MacBook Pro with an Intel chip, everything works fine. I&ap ...

Tool for controlling the layout of the viewport with Javascript

I have experience using ExtJS in the past to create dashboards, and one of my favorite features is the full-screen viewport with a border layout. This allows for easy splitting of a dashboard into panels on different sides without creating excessive scroll ...

Leveraging jquery version 2.2.2 within a grails application

In an effort to ensure compatibility in a Grails project, we are looking to change the JavaScript library versions. We recently added AngularJS 1.5.2, which requires jQuery 2.1+ (source: https://docs.angularjs.org/misc/faq). Our current version of jQuery i ...

The URL for the dynamic import in Workbox is loading incorrectly

For my laravel/vuejs application, I am utilizing workbox and babel dynamic imports. Additionally, I am making use of the laravel-mix and laravel-mix-workbox plugin to compile and generate service worker via generateSW(). The assets load correctly on the r ...

Delete any fields that start with the name "XX"

Here is an example document extracted from a collection: { "teamAlpha": { }, "teamBeta": { }, "leader_name": "leader" } My goal is to remove all fields that begin with "team" from this document. Therefore, the expected outcome would be: {leader_name: "l ...

The getelementbyid function is unable to locate the specified button identifier

As I dive into the world of Javascript, I wanted to create a simple input form with a corresponding response field on my website. However, I encountered an issue where using a basic submit button caused the page to refresh and erase the textfields before ...

The animation came to a halt after a brief period

Here is the code I wrote. When the button is clicked, the 3 containers should start flashing indefinitely, but they stop after a while. I can't figure out why. Any ideas? <!DOCTYPE html> <html> <head> <title></title> & ...

What is the best way to send a Rails AJAX form upon clicking?

I'm looking to implement AJAX form submission in Rails using a button. Here's my current code: Controller: def list @events = ExternalEvent.all if !params[:city_id].nil? @events = @events.where(city_id: params[:city_id]) end respond ...

The renderValue property is malfunctioning in the Material-UI native Select component

Whenever I utilize the native prop in the MUI Select component, the renderValue prop fails to function properly. Additionally, if I attempt to assign a custom value to the value prop, it does not display. Take a look at the code snippet below: const [selec ...

Syntax for private members in ES6 classes

I'm curious to know the most efficient way to declare private members within ES6 classes. In simpler terms, what is the best practice for implementing: function MyClass() { var privateFunction = function() { return 0; }; this.publicFuncti ...

Eliminate the empty choice from the Select dropdown using AngularJS

I recently started exploring AngularJS and I've been facing a problem that I couldn't find a solution for. Whenever I try to select an option from the dropdown, it shows up as blank initially. Here is the snippet of my HTML code: <div ng-ap ...

Adjust SVG size as per parent container in AngularJS custom directive

I have a unique situation where I am integrating an angular directive into a dynamically-sized element. The directive itself is made up of an SVG which adjusts based on the size of the container. I am working on making sure the SVG automatically resizes an ...

Is there a way to keep the text animation going even when I'm not hovering over it with the cursor?

Is there a way to make text continue animating on the page even when the cursor is not placed on it? I understand the hover function, but how can I ensure the text keeps animating without interruption? $(document).ready(function () { $("#start&q ...

An assortment of the most similar values from a pair of arrays

I am seeking an algorithm optimization for solving a specific problem that may be challenging to explain. My focus is not on speed or performance, but rather on simplicity and readability of the code. I wonder if someone has a more elegant solution than mi ...