It appears that Promise.all is not adequately ensuring that all tasks are completed before moving on

In my current project, I am trying to achieve a complex cycle where an HTTP GET request is executed to fetch data, followed by the creation of multiple "subrequests" based on that data. The goal is to ensure that the next iteration of the cycle begins only after all the "subrequests" have been completed. My code snippet for this task looks like:

var end = w/e; // the amount of calls I want to make
(function recursiveCall(index) {
    $http.get('blahblahblah').then(function (response) { // "big" request
        var requests = [];
        for(var i = 0; i < whatever; i++) {
            requests[i] = (function(reqIndex) { // fill the array with a series of (different) requests
                return function() {
                    setTimeout(function() {
                        // use reqIndex to create a different request
                        $http.get('blahblahblah' + reqIndex /* some modification based on i */).then(function (data) {
                            // callback
                        }, function (data) {
                            // error
                        });
                    }, 1000 * reqIndex); // need to pause between each req
                }
            })(i)
        }
        Promise.all(requests.map(function (req) { // execute the array of requests
            return req();
        })).then(function (data) { // I want this to happen only after *all* the requests are done
            // success!
            console.log('all sub-requests done!');
            if(index === end) {
                return 0;
            } else {
                recursiveCall(++index); // repeat with index + 1
            }
        }, function (data) {
            // error :(
            console.log("error");
        });
    }, function (response) {
        // error
    });
})(0);

However, I have noticed that the then() clause of Promise.all() is executing immediately after the "big" request returns with a 200 status, without waiting for all the other subrequests to be completed. This behavior has me puzzled, and I would appreciate any insight into why this might be happening.

Answer №1

To provide further clarity on my point, here is a code snippet that can help demonstrate it:

return new Promise(function(resolve, reject) { 
    setTimeout(function(){

      // When the http callback occurs
      resolve(); // or reject based on your specific situation...

    }, 1000); 
});

If you are working with $q (within an AngularJS application), you may find more information at https://docs.angularjs.org/api/ng/service/%24q

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

developing a deferred commitment by utilizing promise objects

Hi everyone, I've encountered an issue with a JavaScript promise question that's throwing errors function delay(n) { return new Promise((resolve) => setTimeout(resolve, n*1000)); } The expected output should be "It is now 2 seconds later" ...

React is producing a collection of <td>'s

My React code is very straightforward and it runs smoothly: function Columns(){ return ( <React.Fragment> <li>Hello</li> <li>World</li> </React.Fragment> ); } function Example(){ ...

Converting data from a PHP backend to AJAX for further processing

I am currently working on a Laravel project where I need to interact with a payment gateway and continuously check the payment status for three times within 5 seconds. My goal is to pass data from the controller to AJAX code and utilize the setInterval Jav ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

Exporting JavaScript formatting in Netbeans is a breeze

Does anyone know how to preserve the formatting for JavaScript in Netbeans 8.1 when exporting? After clicking on the export button and expanding Formatting, I couldn't find any option specifically for JavaScript. I've thought about locating the ...

Utilize setState in a ReactJS function within an if statement towards the end

Help needed! I'm facing issues trying to use the function setState within an if statement inside another function. Specifically, I'm working on creating a series of Tab components with inline styles that determine their visibility. Before returni ...

Tapping into the space outside the MUI Modal Component in a React application

Can Modal Component in MUI be used with a chat bot? When the modal is open, can users interact with buttons and inputs outside of it? How can this be implemented? I want to be able to click outside the modal without closing it. Modal open={open} onClo ...

Why is my HTTP request callback not being executed?

I've been trying to send an HTTP POST request to a 3rd-party API using a promise method. Oddly enough, the callback function never seems to run, even though when I test the code on its own, the API call is successful. Node.js and the concept of an e ...

The Quivering Quandaries of Implementing Jquery Accordions

For a demonstration of the issue, please visit http://jsbin.com/omuqo. Upon opening a panel by clicking on the handle, there is a slight jitter in the panels below during the animation. In the provided demo, all panels should remain completely still as t ...

Having trouble with installing the most recent versions of React App dependencies

After cloning a project from GitHub, I attempted to install dependencies using npm install, but encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email ...

The selected value is not displayed in the Material UI select component

My select component is showing the menu items and allowing me to select them, but it's not displaying the selected value. However, its handle function is functioning correctly because when I choose an item, the value in the database gets updated. Bel ...

Exploring Node.js with the power of EcmaScript through Javascript Mapping

I am currently using Map in NodeJS version 0.10.36 with the harmony flag enabled. While I am able to create a map, set and retrieve data successfully, I am facing issues with other methods such as size, keys(), entries(), and forEach as they are returning ...

The problem with utilizing the Node `util.inherits` method

I have encountered an issue with a 'this problem' in a Node server. It seems that replacing worker.stuff with worker.stuff.bind(worker) is necessary for it to function correctly. Is there a way to incorporate the bind method into the Worker Clas ...

Mastering data extraction from JSON using React JS (with Axios)

Being new to ReactJS and axios, I am facing a challenge. I need to iterate through JSON data and extract values where the key is a number (e.g. 0, 1, 2...). However, I am unsure how to implement this in my code since the server provides dynamic JSON data ...

Align the text on the same horizontal line

I have been struggling with this issue for hours. Here is my Header.js <div className="navbar-inner"> <h2>Text1</h2> <h3>Text2</h3> </div> This is the content of my Header.css: .navbar-inner { ...

Generating Dynamic Object Keys following Array Mapping

I have a vision of creating a sophisticated data structure resembling the configuration below: slots: { 'slot_1': { id: 'slot_1', associatedCard: {} }, 'slot_2': { id: 'slot_2& ...

What is the process for creating a custom hook in React.js/Next.js?

I encountered a problem while trying to create a hook from my code. Here is the snippet from the hook file: import { useRouter } from "next/router"; const useCurrentPath = () => { const { asPath, locale, defaultLocale } = use ...

Leveraging the outcome of an API request with Protractor

I have developed a small API that generates test data instantly. Each request creates a new user and provides the relevant data. For fetching the data, I utilize the 'request' package: var flow = protractor.promise.controlFlow(); var result = f ...

Is it possible to create a collapse and expand animation that does not involve transitioning the `height

After extensively researching, I have come across numerous articles advocating for the use of transform and opacity for achieving smooth CSS transitions. An example can be found here: The prevailing notion always revolves around: ...the optimization ...

Switch Focus and Collapse Submenus upon Menu Click in Recursive React Menu

I've created a dynamic menu system in React using Material-UI that supports recursion for submenus. I'm aiming to implement the following features: 1. When a menu item is clicked, all other open submenus should close and focus on the clicked men ...