Utilizing API calls within a loop using AngularJS

I need to execute a series of APIs in a loop, but I want the second loop to start only after receiving the result from the last API call in the first loop. How can I achieve this?

for(var i=0; i<array.length; i++ )
    service.getfunction(array[i]).then(function(response) {
      service.getfunction1(response).then(function(response) {
        service.getfunction2(response).then(function(response) {
          service.getfunction3(response).then(function(response) {
             console.log(response);
          });
        });
      });
    });
)

Answer №1

To start, you have the ability to chain promises together in the following manner:

function performTask(index) {
  return service.fetchData(array[index]).then(function(data) {
    return service.processData1(data);
  }).then(function(result) {
    return service.processData2(result);
  }).then(function(finalResult) {
    return service.processData3(finalResult);
  }).then(function(response) {
    console.log(response);
  });
}

This function will produce a promise that resolves once all necessary service calls are completed. Now let's put it into action:

var promise = Promise.resolve(true);
for(var index = 0; index < array.length; index++) {
  (function(i) { //It is crucial to wrap it to prevent passing incorrect index value to performTask
    promise = promise.then(function() {
      return performTask(i);
    });
  })(index);
}
promise.then(function() {
  console.log('All tasks finished');
});

Answer №2

Enclose everything within a function:

// Define the wrapping function 
function RepeatAPI() {
    for(var i=0; i<arr.length; i++ )
        serv.getfunc(arr[i]).then(function(resp) {
          serv.getfunc1(resp).then(function(resp1) {
            serv.getFunc2(resp1).then(function(resp2) {
              serv.getfunc3(resp2).then(function(resp3) {
                 console.log(resp3);

                 // Call the function again
                 RepeatAPI();
              });
            });
          });
        });
    )
}

// Initial function call
RepeatAPI();

Answer №3

To execute a chain of promises sequentially, you can utilize Array.reduce along with the .then() method as demonstrated below:

array.reduce(function(previous, next)
{
    return previous.then(function()
    {
        return service.getFirstFunction(next);
    })
    .then(function(response)
    {
        return service.getSecondFunction(response);
    })
    .then(function(response)
    {
        return service.getThirdFunction(response);
    })
    .then(function(response)
    {
        return service.getFourthFunction(response);
    });
}, Promise.resolve())
.then(function()
{
    console.log("All tasks completed successfully.");
})
.catch(function(error)
{
    console.log(error);
});

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

Error: The code is trying to access the property 'string' of an undefined variable. To fix this issue, make sure to

I encountered an issue after installing the https://github.com/yuanyan/boron library. The error message I received is: TypeError: Cannot read property 'string' of undefined Error details: push../node_modules/boron/modalFactory.js.module.expor ...

What is the most effective way to showcase a list of image URLs in HTML with Vue?

Currently, I am working with an array called thumbnails that holds the paths to various images. My goal is to use masonry in Vue to arrange these images in a grid format, but I'm encountering some difficulties achieving the desired outcome. This is m ...

Executing multiple commands using Node.js TCP communication

I have established a connection to a serial device via the internet using an ethernet to serial device. The communication is facilitated through a small node.js application. The provided code retrieves the necessary information: var net = require('ne ...

Is there a way for me to extract the true text content that is concealed within the page source code?

Is there a way to extract the hidden text "2015-10-31" from a webpage, even though it is not visible in the page source? I am able to scrape the right side of the HTML, but I need to access the value on the left side. I have tried using Selenium to automat ...

What is the Method for Multiplying Two ng-module Values in AngularJS?

In my application, I am utilizing the MEAN stack with AngularJS for the front-end. I have a table that contains two values - 'Payment value' with commas and 'commission' without commas. How can I multiply these two values? For example: ...

How to implement form modal binding using Laravel and Vue.js

There are two models named Tour.php public function Itinerary() { return $this->hasMany('App\Itinerary', 'tour_id'); } and Itinerary.php public function tour() { return $this->belongsTo('App\Tour', ...

What triggers the onmouseout event to occur?

Is the event triggered continuously whenever the mouse is not hovering over the element? Or is it a one-time action when the mouse exits the element? This distinction is crucial for me to determine when the mouse pointer leaves the element, while only wa ...

It can be frustrating to have to refresh the page twice in order to see changes when utilizing the revalidate feature in Next

When I make the REST call to fetch data for my page using the code below: // src/app/page.js const Home = async () => { const globalData = await getGlobalData(); return ( <main'> <SomeComponent data={globalData} /> < ...

Tips on serving a static file from a location other than the public or view directories following middleware in Express JS

I am organizing my files in a specific way. Inside the folder api-docs, I have an index.html file along with some CSS and JS files. My goal is to display the API documentation only for authenticated users. Since I am using Jade for views in this proje ...

Tips for adjusting the dimensions of my chart using JavaScript or Jquery

Utilizing DevExtreme widgets for the creation of a line chart in jQuery as shown below: var dataSource = [{"Date Range": "August-2018", Benelux: 194, Czech_Slovakia: 128, ...

Explore the Benefits of Using MUI V5 Grid Component for Your Box Design

Exploring MUI to delve into the world of React for the first time. Curious about the usage of the Box component alongside the Grid component. The example on the docs showcases this scenario. export default function BasicGrid() { return ( <Box sx={ ...

Trouble with CSS animation when incorporating JavaScript variables from a PHP array

Whenever I use a script to fetch an array of objects from PHP... I successfully display the results on my website by outputting them into Divs. The challenge arises when I introduce CSS animations. The animation only triggers if the variable length excee ...

perform validation middleware following completion of validation checks

Looking to establish an Express REST API, I aim to validate both the request parameters and body before invoking the controller logic. The validation middleware that I have put together is as follows: const { validationResult } = require('express-va ...

The Joi validate() function will return a Promise instead of a value when used within an asynchronous function

Trying to understand how async functions and the Joi.validate() function behave. Below is a function used for validating user input. const Joi = require("joi"); const inputJoiSchema= Joi.object().keys({ name: Joi.string(), email: Joi.string().require ...

Is it possible to modify @page directive(CSS) values from the code-behind(C#) or JavaScript?

Using the @page directive, you can define the printer margins for a page separately from regular CSS margins: <style type="text/css" media="print"> @page { size: auto; /* auto is the current printer page size */ margin ...

The server encountered a 500 Internal Server Error because it could not read the 'username' property of an undefined object

When attempting to register a user in a mongodb database using express, a POST call was made to localhost:3000/users/register The request body included: { "firstName": "Jason", "lastName": "Watmore", "username": "jason", "email": "<a ...

The $route object in Vue is not configured

Currently, I am delving into the realm of Vue router and aiming to achieve programmatic navigation without relying on <router-link> in my templates file. Here is a glimpse of my router and view setup: router = new VueRouter({ routes: [ ...

Issue detected with XMLHttpRequest - "The requested resource does not have the 'Access-Control-Allow-Origin' header."

Currently, I am working on the frontend development of an application using Angular 2. My focus is on loading an image from a third-party site via XMLHttpRequest. The code I have implemented for this task is as follows: loadFile(fileUrl) { const ...

Unable to incorporate additional components into AngularJs Boilerplate

I've been working on an Angular project and decided to utilize a boilerplate for it. You can find the boilerplate I'm using at this link: https://github.com/jakemmarsh/angularjs-gulp-browserify-boilerplate The issue I'm encountering is my i ...

Can you please explain the distinction between the statements var a = b = 2 and var a = 2; var b = 2;

Whenever I try to declare a variable within a function, I encounter an issue. var b = 44; function test(){ var a = b = 2; } However, the following code works without any problems: var b = 44; function test(){ var a; var b = 2; } The global ...