Executing REST API calls from within a loop in AngularJS

for (var i = 0; i < pricingPlans.length; i++) {
    productServices.retrivePricingPlan(pricingPlans[i].Id.Value).then(function (objPricingPlan) {
        productServices.createPricingPlan(objPricingPlan.data).then(function (objNewPricingPlan) {
            var newPlanID = objNewPricingPlan.data.PricingPlan.Id.Value;
            console.log("New ID");
            console.log(newPlanID);
            console.log("Old ID");
            console.log(product.PricingPlanAssociations[i].PricingPlanId.value);
            //  product.PricingPlanAssociations[i].PricingPlanId.value = newPlanID
        });
    });
}

In the process we have outlined, I am executing REST calls within a loop, aiming for them to run in a specific sequence:

  1. Retrieve pricing plan[i]
  2. Create pricing plan[i]
  3. Create product[i]

However, when observing the console log, the calls appear to be executed out of order.

What steps should I take to ensure that the pricing plans are processed in the desired order within the for loop?

PLEASE NOTE: The methods retrievePricingPlan and createPricingPlan involve calls to $http.post().

https://i.stack.imgur.com/50wzL.jpg

Answer №1

Due to the asynchronous nature of AJAX calls, the order in which they are executed can vary within a synchronous loop. However, calls labeled as "dependent" will always be executed in the correct sequence. For instance, Retrieve will always be invoked before Create in the promise chain.

To ensure that these calls are processed sequentially, consider implementing a queue system to manage their order within the asynchronous environment.

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

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

It appears that the ngRepeatWatch feature is causing a slowdown in Batarang

After reviewing the Batarang analysis of my AngularJS app, I have discovered the following: ngRepeatWatch | 64.2% | 136.0ms Surprisingly, this instruction takes up 10 times more time than the next reported instructions. Could this indicate that I am pot ...

Show selected rows within ng-repeat regardless of the filter applied

Every character name in the list has a checkbox next to it. The content of the div changes based on the text entered into the search box. If I check "Harry" in the div, and then type "Tom" in the search bar, "Harry" will disappear from the div. If I delet ...

Is there a way to make Express.js pass parameters with special characters exactly as they are?

I am currently working on a project within the freeCodeCamp "API and Microservices" curriculum that involves using Express.js to handle routes. The project itself is relatively straightforward, with some pre-defined routes and others that need to be creat ...

Utilizing Angular 1.4.8 and lodash to effectively parse an array of objects with conditional parameters

DEVELOPER TOOLS Angular version 1.4.8, lodash version 4.0 SOLUTION IMPLEMENTATION After building on Derek's code contribution below, I have arrived at the following solution. It was necessary to make adjustments as using _.property() or _.map() ch ...

AngularJS Multi-Window Feature Plugin

Our team is currently working on a large scale application built in Angular. This application consists of multiple modules, each containing over 100 pages related to garment ERP functionalities. Our client requires the ability to view and manage multiple p ...

Once the page is refreshed, the checkbox should remain in its current state and

I have a challenge with disabling all checkboxes on my page using Angular-Js and JQuery. After clicking on a checkbox, I want to disable all checkboxes but preserve their state after reloading the page. Here is an example of the code snippet: $('# ...

An issue arises when ng-pattern fails to recognize a regular expression

My form includes inline validation for a specific input field. <form name="coForm" novalidate> <div> <label>Transaction: </label> <input type="text" name="transaction" class="form-control" placeholder="<Dir ...

Step-by-step guide to retrieving the value of a duplicate input field with identical IDs in Angular4

This is the form I am working on: <button (click)="M_add()">Add</button> <tbody id="_tbody"> </tbody> Whenever the add button is clicked, it triggers the creation of an input field. let tbody = document.getElementById("_tbody"); ...

Choose a sibling element using CSS styling

As I'm developing an AngularJS component, I am on the quest to identify ANY sibling of a particular tag, irrespective of whether they are div, span, or p. I'm hoping for a CSS-native solution that resembles something along the lines of div:siblin ...

How can I delay the ng-show element until the ng-hide CSS transition has finished?

Looking for a simple solution to my implementation issues. I'm faced with the following DOM setup: <h1 class="fade" ng-repeat="child in parent.children" ng-show="parent.activeChild == child">@{{ child.title }}</h1> How can I smoothly fad ...

Having trouble accessing an AngularJS $scope variable because it is coming up as undefined

Currently, I am developing an Electron application using AngularJS for the frontend. Since node.js operates at the OS level while Angular runs at the client level, communication between the two is achieved through IPC (Inter-Process Communication) implemen ...

Switching views in AngularJS by using a controller to control the content displayed in the

My JavaScript web app utilizes AngularJS to simplify tasks, but I've encountered an issue. I'm trying to change views from an ng-controller using $location.path, but for some reason, the view isn't updating even though the path in the $loca ...

The child object in Typescript is characterized by its strong typing system

Looking to convert plain AngularJS code to Typescript? Take a look at this example: app.someController = function ($scope) { // var $scope.Data = null; var $scope.Data: SomeCollection = null; I need to associate Data with scope and specify it as type ...

Navigating back to the previous page while retaining modifications using AngularJS

When I use the products table to conduct an advanced search, view details of a specific item and then click on the cancel button to return to the list, all my research inputs are reset... Is there a way for me to go back to where I was before? Can I retri ...

Update the nested radio button to a new value

I have a series of radio button lists generated using ng-repeat. I've managed to capture the selected item successfully. Now, I am attempting to set the default value for the radio buttons. Could someone please provide assistance? Below is my code sni ...

Monitoring a variable inside a service using AngularJS

I am currently in the process of developing a web application using AngularJS. My application consists of a primary view (Index), a child view (Dashboard), and a grandchild view (Raiding The Rails). http://localhost:4000/#/dashboard/raiding-the-rails/1 ...

Executing AJAX requests in an AngularJS application within a Cordova mobile app

After developing an app with Ionic Framework, AngularJS, and Cordova, I encountered a problem with AJAX calls to PHP files. While these calls work flawlessly in a browser, they fail within the app itself. Interestingly, the app is able to render internet p ...

Retrieve the values of private variables within a defined function

While experimenting with typescript, I have encountered an issue that I can't seem to resolve. My project involves using Angular, so I will present my problem within that context. Here is a snippet of my code: class PersonCtrl{ private $scope: I ...

Mapping fields in Spring to JSON can be tricky, especially when dealing with fields that can be

In my object, there is a String value field which can contain either true or false. The issue arises when Spring/Jackson maps this to value: "true" as a String, causing problems with certain angularjs ng-model mappings that expect a boolean. Is there a way ...