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

Is it not possible to include Infinity as a number in JSON?

Recently, I encountered a frustrating issue that took an incredibly long time to troubleshoot. Through the REPL (NodeJS), I managed to replicate this problem: > o = {}; {} > JSON.stringify(o) '{}' > o.n = 10 10 > JSON.stringify(o) ...

Using Multiline Strings for Arguments

Is there a way to successfully pass multi-line strings containing spaces and tabs as a parameter to an express server? Below is the Express.js code snippet which accepts the parameter: app.get('/:prompt', async (req, res) => { ...

Designing an image transformation page by segmenting the image into fragments

Does anyone have insight into the creation process of websites like this one? Are there any plugins or tools that can assist in building something similar? ...

Generating a unique JavaScript array by extracting data from an HTML input element

I am working on a basic HTML form that requests a number between 1 and 10 from the user. Depending on this number, I aim to generate a new array. Currently, the code displays an alert box with the newly created array, but my end goal is to have a table p ...

What is the best way to access and extract values from Material-UI TextFields within a Dialog component using React?

Here is the dialog that I am working with: <Dialog> <DialogContent sx={{ display: "flex", flexDirection: "column" }}> <TextField id="item-name" label="Item Name" /> <Tex ...

Is there a way to insert rows and columns into the table headers using React Material UI?

I am new to working with material UI and I am having trouble figuring out how to add columns in the table header. The image below shows what I am trying to achieve - under "Economics", there should be 3 columns, each of which will then have two more column ...

Utilize JavaScript to load images at random within a Qualtrics loop and merge block

I'm currently putting together a survey on qualtrics using a block with loop and merge functionality. I've encountered an issue where, after the first iteration, the images I'm loading through javascript start disappearing. Although I can br ...

Guide on utilizing personalized fonts with Handlebars and Puppeteer

I have a Handlebar template that I am converting to PDF using Puppeteer. My question is how can I incorporate custom fonts? Currently, I have a static folder declared in my app.js file like this: app.use(express.static(path.join(__dirname, 'assets&ap ...

The 'admin' attribute is not found in the 'Object' data type

I have been facing this issue for quite some time now. The backend API response is indicating that a certain property does not exist, even though it clearly does. My Angular application suddenly started showing 18 errors today, and I am at a loss on how ...

Utilizing the .map() function to retrieve an object from an array without a key

Exploring Dialogflow, I aim to retrieve the speech value for the object in the messages array that lacks a platform key: "messages": [ { "type": 0, "platform": "skype", "speech": "FOO" }, { "type": 0, "platform": ...

Encountering an issue with Invariant Violation when attempting to retrieve a frame that is outside of the specified

I have created a VenueList component for my React Native app. I want to utilize the FlatList component to display a list of venues, but I keep encountering an error message that says "Invariant Violation tried to get frame out of range index" (refer to the ...

Is it a Mozilla Firefox glitch or something else?

After writing the code, I noticed a bug in Firefox and a small bug in Chrome. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> ...

Adjusting the height of an element based on changes in screen width or height using Angular

I'm in the process of developing a directive that can detect changes in screen size, either width or height, and adjust the height of my element accordingly. The main goal is to have my element extend all the way to the bottom of the browser window. ...

Is the Coinmarketcap API currently experiencing downtime in Python?

I've been relying on the Coinmarketcap Api https://api.coinmarketcap.com/v1/ticker/ for a while now. It was a great resource providing almost real-time data (every 130s) in a convenient .json format and best of all, it was free! However, it seems lik ...

What is the best way to halt a specific function in jQuery?

I recently developed a website for my photographer friend, and I implemented a feature where the home page is initially blurred. Visitors can click a button to unblur the content. While the functionality works smoothly, there's one issue - every time ...

Using webGL for rendering drawElements

I am working with face-indices that point to specific points to draw triangles in a loop. Unfortunately, when executing my code, I encountered the following error in the web console: WebGL: drawElements: bound element array buffer is too small for given c ...

What is the best way to set values for the outcomes of a jQuery/AJAX post?

When sending data to a php page using jquery, I aim to receive the response from the page and store it in php variables on the original page without displaying results in the HTML or appending a DIV. Here's an example of how this can be achieved: Sam ...

Issue Installing Npm Package (detected 23 security vulnerabilities)

My attempt to install the package resulted in an error message. How can I resolve this issue? ...

Selenium is encountering a maximum call stack size error while attempting to access Highcharts

This particular issue is a bit complex. My goal is to retrieve highchart data from a selenium-controlled Chrome browser using the driver.execute_script method and injecting some JavaScript: driver.execute_script("return $('#chartID').highcharts( ...

The request is being rejected due to an unrecognized parameter: [mapping]. This is causing an ElasticSearch Index Creation error

I am new to elasticsearch and struggling with getting basic functionalities to work after just two days due to my limited knowledge. My main objective is to create a crud application using Node.js + ElasticSearch. I am currently facing issues with creatin ...