Linking numerous promises generated by a for loop

After delving into the concept of promises through this resource, I grasped the fundamental idea behind it.

var parentID;

$http.get('/api/user/name')
  .then(function(response) {

  parentID = response.data['ID'];
  for (var i = 0; i < response.data['event-types'].length; i++) {
    return $http.get('/api/security/' + response.data['event-types'][i]['key']);
  }

  })
  .then(function(response) {

    // Only one result from the multiple promises in the loop is returned in the response
    // Implement logic using parentID; 

  });

However, my specific scenario demands creating and chaining multiple promises. Despite attempting to chain them as shown above, only one promise generated from the for loop gets executed.

How can I effectively continue chaining all promises while maintaining access to the variable parentID?

Answer №1

Utilizing $q.all is recommended due to its seamless integration with the AngularJS digest cycle.

var parentID;

$http.get('/api/user/name')
  .then(function(response) {

      parentID = response.data['ID'];
      var promiseList = [];
      for (var i = 0; i < response.data['event-types'].length; i++) {
          var iPromise = $http.get('/api/security/' + response.data['event-types'][i]['key']);
          promiseList.push(iPromise);
      };
      return $q.all(promiseList);

  })
  .then(function(responseList) {

       console.log(responseList);

  });

According to the documentation:

all(promises);

Aggregates multiple promises into a single promise that resolves when all input promises are resolved.

Parameters

An array or hash of promises.

Returns

Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.

--AngularJS $q Service API Reference -- $q.all

Answer №2

To improve efficiency, you can use Promise.all() and swap out the traditional for loop with Array.prototype.map()

  var parentID;

  $http.get('/api/user/name')
  .then(function(response) {    
  parentID = response.data['ID'];
  return Promise.all(response.data['event-types'].map(function(_, i) {
    return $http.get('/api/security/' + response.data['event-types'][i]['key'])
    })) 
  })
  .then(function(response) {

    // response only returns one result of the many promises from the for loop
    // perform actions with parentID; 

  })
  .catch(function(err) {
    console.log(err);
  });

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

Turning off v-navigation-drawer for certain routes in Vue.js

I currently have a v-navigation-drawer implemented in my webpage using the code below in the App.vue file. However, I am looking to disable it on certain routes, such as the landing page: <v-app> <v-navigation-drawer id ="nav" persistent : ...

There seems to be an issue with the DownloadDir functionality of the node-s3-client library, as

I am currently using a node s3 client library called 'node-s3-client' for syncing directories between S3 and my local server. As per the guidelines provided in the documentation, here is the code I have implemented: var s3 = require('s ...

Choosing all components except for one and its descendants

I am searching for a method to choose all elements except for one specific element and its descendant, which may contain various levels of children/grandchildren or more. What I'm trying to accomplish is something like... $("*").not(".foo, .foo *").b ...

Identifying and Blocking Users from Accessing External Domains Outside of the Angular Application

I am working on an angular application and I need to implement a feature where I can detect when a user navigates outside of the app domain from a specific component. For instance, let's say the user is on the upload component processing important in ...

How can we utilize data retrieved from Mongodb in Express and pass it to a Jade view using the res.render function?

Within my node/express application, I need to pass data retrieved from mongoose to my jade view. The code below in routes.js accomplishes this task: app.get('/newrequest', function (req, res) { Account.find({}, function (err, data) { ...

Substitute all items identified by a particular tag with a component

Is it possible to replace elements with React? I am interested in replacing all elements with a specific tag with an input field when an event like clicking an 'edit' button occurs. I have experience doing this with jQuery, but I would prefer us ...

The Ajax page does not respond to click events when the function is declared within $(function(){ }) block

Create two functions as shown below: <script> $(function () { function myFunctionB() { alert("ddd"); } }) function myFunctionA() { alert("ddd"); } </sc ...

Creating an array by extracting items from a textarea that are separated by line breaks

I am working with a textarea that has the id #list : $text = $('#list').val(); The goal is to split this text into pieces and place each piece as a new item in an array. This array will then be sent to PHP, where I can utilize it in a foreach l ...

Trouble with predefined JavaScript in Mongodb situation

Encountering the error "Missing ";" before statement" in Mongodb Atlas Online is frustrating for me as a newbie. Despite my efforts, I can't seem to figure out why the following code snippets are causing this issue: const counter = await counterCollec ...

Example of AngularJS UI-Router Login Feature

Currently, I am delving into the realms of angularjs and bootstrap to develop a web application that will consist of two distinct sets of views - public and private. In the public view, all users will have access to it and there will be a specific top men ...

Displaying PDF files on the internet without allowing them to be downloaded

How can I display PDF files on my website without allowing them to be saved or downloaded? Is there a way to prevent browsers from saving or downloading the PDF files? ...

How can I resolve a JavaScript issue that occurs when accessing a property within the same object?

Displayed below is a snippet from a much larger JavaScript object within my project. Thousands of lines have been omitted to focus solely on the area in question... Line 6 is specifically where the issue lies. Here's a concise example involving Java ...

JavaScript, detecting repeated characters

I need to create a script that checks an input box (password) for the occurrence of the same character appearing twice. This script should work alongside existing regex validation. I believe I will need to use a loop to check if any character appears twice ...

How can I quickly duplicate the design of a JSON Object?

Perhaps the title is a bit basic. Essentially, I am looking for something similar to mysqldump ... --no-data .... For instance, I have a JSON object structured like this: { "key1" : "value1", "key2" : "value2", "key3" : { "key3a" : 1, "key ...

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

No response data being displayed after Angular post request

After sending a POST request via Postman, I received the expected response with a status of 400. However, when I tried sending the same request using Angular's http.post in the browser, I only received a 400 error without any response data. https://i ...

Ordering by the scope function and then by a specific field can be achieved by following these

Is it possible to order by the result of getTotal() and then arrange by quantity in descending order? <!DOCTYPE html> <html ng-app="shop"> <head> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14 ...

The beta version of Angular 2.0 introduces the BrowserDomAdapter for easy access to the DOM

I have a Component in Angular 2.0 that is attempting to utilize the DOM Adapter API from Angular's BrowserDomAdapter documentation. The initialization of this DomAdapter can be found here. However, I am uncertain about whether the Dom Adapter needs t ...

A guide on applying bold formatting to a specific section of text in React

I have a collection of phrases structured like so: [ { text: "This is a sentence." boldSubstrings: [ { offset: 5, length: 2 } ] } ] My goal is to display each phrase as a line using the following format: ...

What is the process for sending a parameter in getStaticProps within Next.js

Is there a way in NextJS to call an API when a user clicks the search button and display the relevant result? Thanks for your input! The API I'm currently utilizing is , with "Steak" referring to the specific food item of interest. In my development ...