How can we trigger a function once the API requests within a for loop have completed?

Within this for loop, a maximum of 'time' iterations are specified. With each iteration, a GET call is made to retrieve data that must be added to the obj object.

I am seeking a method to determine when all 3 GETS have been completed along with the for loop, prior to executing the TagFactory.buildSavedView(obj) line. Any suggestions?

for (var i = 0; i < termIDs.length; i++) {
    ApiFactory.getTagData(tickers[i], termIDs[i]).then(function(data) {
        singleTagArray.push(data.data.tickers);

        var updatedTag   = TagFactory.renderDirections(singleTagArray, null, period);
            newTagObject = updatedTag[0];

        tags.push(newTagObject);

        finishObjSetup(tags);
        console.log('viewHeaderDirect > obj: ', obj);
    });
}

TagFactory.buildSavedView(obj);
vm.loadSavedModal = false;

Answer №1

To ensure all promises are executed before proceeding, utilize the $q.all method by creating a promise array and passing it to $q.all. This will trigger the .then function only when all promises have been resolved.

Code Snippet:

var promises = [];
for (var i = 0; i < termIDs.length; i++) {
    var promise = ApiFactory.getTagData(tickers[i], termIDs[i]).then(function(data) {
        singleTagArray.push(data.data.tickers);

        var updatedTag   = TagFactory.renderDirections(singleTagArray, null, period);
        newTagObject = updatedTag[0];

        tags.push(newTagObject);

        finishObjSetup(tags);
        console.log('viewHeaderDirect > obj: ', obj);
    });
    promises.push(promise); //creating promise array.
}

$q.all(promises).then(function(){
    //this code block will execute after all promises have been resolved
})

Answer №2

To keep track of progress, a straightforward counter can be implemented:

var count = 0;

for (var index = 0; index < termIDs.length; index++) {
  ApiFactory.getTagData(tickers[index], termIDs[index]).then(function (data) {
    count++;
    singleTagArray.push(data.data.tickers);

    var updatedTag = TagFactory.renderDirections(singleTagArray, null, period);
    newTagObject = updatedTag[0];

    tags.push(newTagObject);

    finishObjSetup(tags);
    console.log('viewHeaderDirect > obj: ', obj);

    if (count === termIDs.length) {
      TagFactory.buildSavedView(obj);
      vm.loadSavedModal = false;
    }

  });
}

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

Remove the scrollbar from the iframe and instead display a scrollbar on the page in its place

Currently, I am facing an issue with the vertical scrollbar on an iframe. I want to remove it so that the scrollbar appears on the main page instead. This way, I will be able to scroll the content of the iframe using the page's scrollbar. I managed to ...

Eliminate any blank spaces in the string before comparing the option value to determine whether the DIV should be

I am trying to create a function that hides or shows a specific DIV based on the option value selected from the product. Due to automatic addition of option values by Shopify, some options have more than one word with spaces in between. Since I cannot chan ...

Is the Date Epoch a reliable form of unique identification?

Currently, I'm developing a Node API and encountered a situation where I need to create a unique 15-digit random number for a model without using autoincrement. The challenge is to ensure that the generated number is not trivial. I am hesitant about ...

How can we best organize a VueJS application to accommodate this specific logic?

I am currently working on an app that needs to display data fetched from multiple sources based on a condition. The issue I am facing is that the process of fetching, organizing, and returning the data varies depending on the source, sometimes even requiri ...

Determine the quantity of items within a JSON array

There is a json array located at the following url: http://localhost/heart/api/restApiController/dataset.json The structure of the json array is as follows: [ { Weight: "3", Smoking: "1", Exercising: "0", Food_habits: ...

Tips for establishing a fixed point at which divs cease to shrink as the browser size decreases

There are numerous dynamically designed websites where divs or images shrink as the browser size decreases. A great example of this is http://en.wikipedia.org/wiki/Main_Page The div containing the text shrinks proportionally to the browser size until it ...

Angular: the directive following the expression

Here is a directive and its corresponding definition that I'm working with: <div editor> {{markdown.html}} </div> The directive editor() looks like this: function editor() { return { restrict: "A", link: function (scope, ele ...

Sending data through forms

I'm having trouble storing values input through a dropdown menu in variables event1 and event2, despite trying global declarations. How can I successfully store a value to both variables and pass it to the JavaScript code? Thank you. <!DOCTYPE HT ...

The Heroku Node.js application encountered an issue when trying to apply the style due to an incompatible MIME

As a complete beginner in Node.js and Express, I am encountering some errors from the console. When trying to load my CSS file from '', I receive the following error: "Refused to apply style because its MIME type ('text/html') i ...

Mapping an array in ReactJS based on the specific order of another array

In my experience with Unmitigated, the answer proved beneficial. If you're arriving from a Google search, please scroll down for more information. Order: [ "567", "645", "852", "645", "852", "852 ...

Enhancing angular service with additional parameters

UPDATE: angular.extend and Object.assign both work fine, but which one is the better choice? I am facing an issue where adding more values to an angularjs service variable overwrites the previous value. Here is a sample code snippet: var testModule = ang ...

Htmlunit driver encounters difficulty executing Javascript

Recently, I switched my Selenium test from using FirefoxDriver to HtmlunitDriver in Java. The test was running smoothly in the Firefox browser but encountered an issue when I made this change: driver = new FirefoxDriver(); to driver = new HtmlUnitDriver ...

The concept of nested views in Angular UI-Router allows for a

How can I successfully implement nested views, where after logging in the user is redirected to in.html, and all links within in.html are directed to a ui-view? Currently, all links redirect to a new page. index.html <!-- more HTML --> <body ng- ...

Can you provide tips on using Ajax to store a cache file?

I've created a javascript/ajax function that retrieves a json file from an external server. The functionality I'm trying to implement includes: Fetching the json file from the external server Saving the json file on the local server Checking if ...

Tips for sending a JavaScript object to a Java Servlet

I'm facing a challenge with passing a JavaScript object to a Java Servlet. I've experimented with a few approaches, but nothing has worked so far. Below is the code snippet I've been working on: $.ajax({ url: 'TestUrl', d ...

Styling Angular Components with Inline CSS

In my HTML, I am using $scope to set the background image of a div tag using inline styling. Here is the code snippet: <div class="banner" style="background-image: url('{{bannerImage}}'), url('images/generic.jpg')"></div> ...

Trigger a jQuery event when a particular element has finished loading

Is there a way to globally detect when any element (such as textarea) is displayed on the page in order to perform a specific action? The element could also be added dynamically through an AJAX request. // This code snippet is just an illustration of the ...

When changing the dropdown option on a separate page in React/Next JS, all checkboxes show the clicked style as a result of utilizing useState

I have implemented checkboxes for three different categories: "Types", "Price", and "Categories". They function correctly, with data being passed to a separate checkbox component without any issues. The problem arises when I click a checkbox and then inte ...

Switching to a different view in a React Native application

I am encountering difficulties while navigating between pages in my React Native application. Whenever I try to use the button, an error message pops up saying: TypeError: undefined is not an object (evaluating '_this.props.navigation'). My app c ...

I'm having trouble getting the [resetFilterOnHide]="true" functionality to work with primeng 5.2.7. Can anyone provide a solution for this issue?

I'm experiencing an issue with the p-dropdown component where the [resetFilterOnHide]="true" attribute isn't working as expected. When I type in the filter bar, close the dropdown by clicking outside of it, and then reopen it, the entered filter ...