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

Combining video.js and vue.js for seamless integration

Can anyone guide me on how to display a youtube video using a video.js player within vue.js? I'm new to integrations and not sure what it entails. Any assistance will be greatly appreciated. ...

Accessing a child component's method within a parent component by making a call to it

I am facing an issue where I need to invoke a method in a child component from its parent component. Here is the specific scenario: Parent Component Example // ParentComponent.js class ParentComponent extends Component { render() { ret ...

Having trouble with the functionality of Bootstrap's nav-tabs 'show' feature?

I'm having some issues with adding a search box to my glossary. The glossary is created using nested unordered lists (ul) within another ul that has classes of "nav-tabs" and "bootstrap". In the JavaScript code, I am using the following snippet: $j(& ...

What is the best way to transfer an integer from my main application to a separate JavaScript file?

Currently, I am developing a complex code using React Bootstrap and focusing on creating a Dropdown list that fetches data from the backend database. <Dropdown> <Dropdown.Toggle variant="success" id="dropdown-basic"></D ...

Angular JS basic API: Displaying only information that starts with the term 'request'

I've been given the task of developing a straightforward AngularJS API. I have managed to set up the basics for displaying data, but I'm facing an issue where the table only retrieves data from the JSON file if it starts with "request". As a resu ...

Why is my "webpack" version "^5.70.0" having trouble processing jpg files?

Having trouble loading a jpg file on the Homepage of my app: import cad from './CAD/untitled.106.jpg' Encountering this error message repeatedly: assets by status 2 MiB [cached] 1 asset cached modules 2.41 MiB (javascript) 937 bytes (rjavascript ...

Error: AJAX response shows as NaN, indicating that the requested resource was not found

Attempting to create a search engine using AJAX. When typing in the search box, nothing happens. After inspecting the element and opening the console, an error message is displayed: script.js:19 GET http://localhost/var/www/html/pendaftaran-siswa/NaN 404 ( ...

What is the best way to track all method calls in a node.js application without cluttering the code with debug statements

How can I automatically log the user_id and method name of every method called within a javascript class without adding logger statements to each method? This would allow me to easily track and grep for individual user activity like in the example below: ...

Transferring data between jQuery and other global JavaScript variables

I'm facing a challenge when trying to make functions I created in jQuery access JavaScript values defined elsewhere. For instance, I have a function set within my jQuery code. var parentImg = ''; //global variable. $(document).change(funct ...

JavaScript is unable to post content or access elements

Check out the following code: <div class="col-2"> <div class="input-group"> <label class="label">Name</label> <i ...

A guide on mapping an array and removing the associated element

I have an array called responseData, which is used to display the available card options on the screen. public responseData = [ { id: 1399, pessoa_id: 75898, created_at: '2022-11-08T16:59:59.000000Z', holder: 'LEONARDO ', validade: ...

"Creating a Hyperlink that Navigates to Specific Content Within a

I have a situation where I am trying to link to sections on the page contained within collapsed fieldsets. My goal is that when a user clicks on this link, the page should scroll down and automatically expand the fieldset to display the content inside. E ...

What is the process for extracting the value of a checkbox generated through JavaScript?

I recently came across a helpful post on Stack Overflow that provided sample code demonstrating how to display multiple list of checkboxes dynamically on a dropdown list. The function in the code was exactly what I needed for my webpage. However, I encount ...

Return user to the previous webpage upon successful login using Node

I am looking for a way to redirect users who are not logged in from an individual post's page to the login screen, and then back to the post after they have successfully logged in. Here is my login route: router.get('/login', function(req, ...

Tips for formatting dates in Angular 6

I am currently working on a function that displays real-time dates based on user input. Currently, when the user enters the input, it is displayed in the front end as follows: 28.10.2018 10:09 However, I would like the date to change dynamically based on ...

How to properly structure a Vue file in vscode to meet eslint guidelines

Essentially, what I am seeking is uniformity in: the way vscode formats my .vue file how the eslint checker scans my .vue file when I execute npm run .... to launch the server or build the target Currently, after formatting my document in vscode and then ...

Fluid sifting and interactive webpage

I'm almost done with my website, but I'm facing a problem. There are 3 blocks of text on my page - 2 static and 1 dynamic. When I click a button, the page should change, which is working fine. However, when I added smooth scroll to the website, ...

Handling events in AngularJS UI-Grid

Could someone please clarify the role of gridApi in ui-grid and the significance of the onRegisterApi event? Additionally, what is the sequence of events that occur when a grid is being rendered? ...

How to obtain the current URL of an iframe?

After coming across what seems to be a similar question, I still have to ask for clarification because I couldn't find a clear answer. Allow me to elaborate on my project, I am working on an online store where we offer two types of products, The fi ...

How can I send arguments to limit the use of 'E' directives in order to create a dynamic template?

I'm looking to convert some HTML into a directive but I am unsure about how to create directives with dynamic templates. My goal is to pass parameters to the template so that it can be reused with different values. Currently, I have passed parameters ...