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

Adjust tool tip text on the fly

As a beginner, I created a test table and now I want to make the tool tip text change dynamically when I hover over the table with my mouse. Ideally, I would like the tool tip text to correspond to the content of the table cell. Currently, I only have stat ...

Transforming a JSON object into a list in C#

After exploring similar posts without success, I am reaching out here for help. I have a Json data stored in a hidden field that I am trying to access in the code behind file of my markup page. My goal is to convert this Json into a List and bind it to a ...

Finding maximum values by key in Mongoose

Welcome to My Schema let schema = new mongoose.Schema({ property: String, numericValue: Number }, { timestamps: true }); In my database, I store various statistics like: let entryA = { property: "visitors", numericValue: 120 } let en ...

Button Vote in Bootstrap is unresponsive

I have a voting system implemented on my website using normal CSS buttons, and it works perfectly fine. However, when trying to integrate it with Bootstrap buttons, it seems to not function properly. I am looking to switch to using Bootstrap buttons for t ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

What is the process for configuring NextJS to recognize and handle multiple dynamic routes?

Utilizing NextJS for dynamic page creation, I have a file called [video].tsx This file generates dynamic pages with the following code: const Video = (props) => { const router = useRouter() const { video } = router.query const videoData = GeneralVi ...

Angular displaying undefined for service

I have created a service for uploading images to a server, and I am encountering an issue when calling this service from my controller. The error message indicates that the function 'uploadFileToUrl' is undefined. Below is the code for my servic ...

Implementing restify on a website that mandates user login authentication

Currently, I am operating a REST API server using restify. In addition, my front-end consists of angularjs with html, css, and js files hosted on an Apache webserver. The next step is to implement user login authentication for this webapp. Access to the w ...

Updating the handler function for AutoComplete with Checkbox in Material UI using React JS

I am looking to include an <AutoComplete /> field in my form. The options for this field are fetched through a get request, and here is the result displayed in the console. [ { "uid": "c34bb0ed-9f63-4803-8639-a42c7e2a8fb0&q ...

Troubleshooting Issues with Ajax Functionality

I've been struggling with this ajax code that doesn't seem to be functioning as expected. It keeps returning the else statement instead of acknowledging a successful result. When I ran the dologin.php file, it did return 1 successfully. Thank you ...

Upon attempting to send a POST request with PostgreSQL, the following error is displayed: "Invalid input syntax for type integer: '12 Pro'"

I encountered an error while attempting to send a POST request using PostgreSQL/Sequelize. Can anyone help me identify the issue in this code? async create(req, res, next) { try { let { name, price, brandId, typeId, info } = req.body; c ...

Utilizing Ajax and Jquery/JavaScript to dynamically generate HTML elements when data surpasses zero

I have a unique situation where I am dynamically populating an HTML element with divs and data retrieved from a PHP script using JSON. The data is constantly changing, so I am utilizing EventSource (SSE) for real-time updates. <div class="row state-ove ...

Specialized express Validator for 2 particular fields

I currently have 2 custom validators set up for the fields email and phone. check('phone') .not() .isEmpty() .withMessage('Phone should not be empty') .custom(async phone => { const phoneCheck = await ...

typescript scrolling location

In my Angular UI code, I have a component class that includes the following structure: app.component.html //... <div class="banner"> <p-dialog [(visible)]="displayCOI" styleClass="coiDialog" [contentStyle]=" ...

I'm sorry, but we were unable to locate the module: Error: Unable to find 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib'

Encountering an error when building a react app on production: Module not found: Error: Can't resolve 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib' Node Version: Node version 18 Steps taken in Docker Production: npm install - ...

Is it possible to trigger an ajax function two times using the onchange event?

Here is my custom ajax function: var customRequestObject = false; if(window.XMLHttpRequest){ customRequestObject = new XMLHttpRequest(); } else if (window.ActiveXObject){ customRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); } function f ...

JavaScript utilizing an API to retrieve specific data values

Below is some API Data that I have: [ { "symbol": "AAPL", "name": "Apple Inc.", "price": 144.98, "changesPercentage": -1.22, "change": -1.79, ...

Tips for capturing an error generated by a child component's setter?

I've created an App component that contains a value passed to a Child component using the @Input decorator. app.component.html <app-child [myVariable]="myVariable"></app-child> app.component.ts @Component(...) export class AppC ...

The issue of nested form serialization not functioning properly in JQuery has been identified

I am currently in the process of developing a web application. One particular page within this application contains a form, called form1, and I am inserting another page with its own form, form2, inside of form1. Each form contains their own set of values. ...

What causes queryAsync() to generate additional metadata?

Following the instructions provided in a response to a question, I utilized queryAsync() and it is functional. However, it is appending excessive meta data to my query result, which was initially a simple query. This is the code snippet I am using to exec ...