AngularJS: Iterating through data and calling a callback function

When I attempt to fetch multiple JSON files in a loop, I encounter an issue where the callback function only retains the last key of the loop for each result.

Here is how it is called:

deckbuilderApp.factory('DeckFactory', ['$http', '$rootScope', 'DataFactory', function($http, $rootScope, DataFactory) {

  var cardColors = {"white":{}, "blue":{}, "black":{}, "red":{}, "green":{}, "colorless":{}};
  var cardColorsCheck = {"white":true, "blue":true, "black":true, "red":true, "green":true, "colorless":true};

  return {
    fetchCardColors: function() {
      for (key in cardColors) {
        if (cardColors.hasOwnProperty(key)) {
          DataFactory.cardColors(key, function(cardIds) {
            console.log("GOT COLORS FOR " + key);
            cardColors[key] = cardIds;
          });
        }
      }
    }
  }
}

This is how it is requested:

deckbuilderApp.factory('DataFactory', function($http) {
  return {
    cardColors: function(color, callback) {
      $http({
        method: 'GET',
        url: 'js/cardColors/' + color + '.json'
      }).success(callback)
    }
  }
}

Although the data is successfully fetched, the log always displays "GOT COLORS FOR colorless" as it processes the last key in the loop.

Answer №1

This code snippet demonstrates the concept of asynchronous execution in JavaScript:

for (var i = 0; i < 100; i++) {
    setTimeout(function () {
        console.log(i);
    }, 0)
}

The result will be printing number 100 to the console 100 times, due to the async nature of the for loop.

To avoid this behavior, you can use the let keyword or create a closure:

for (var i = 0; i < 100; i++) {
    (function (i) {
        setTimeout(function () {
            console.log(i);
        }, 0)
    })(i)
}

In modern JavaScript (ES6), you can simply use the let keyword to achieve the same result:

for (let i = 0; i < 100; i++) {
    setTimeout(function () {
        console.log(i);
    }, 0)
}

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

Encountering Null values in form collection during submission via ajax in ASP.Net MVC. What could be the underlying problem?

Trying to use an ajax call to save data, but receiving null values for the Model in the action result. HTML @using (Html.BeginForm("addaboutftw", "AboutFtw", FormMethod.Post, new {@class = "form-horizontal", role = "form", @id = "addaboutftw_frm", @name ...

Issue with binding classes dynamically in vue with svg elements

I'm attempting to create a custom typing program for one of my students using SVG to display the words and class binding with Vue.js. The goal is to change the color of the characters when the correct key is pressed by the user. However, I've enc ...

Issue with resetting JavaScript input value in onblur event

I have a function where I'm trying to clear the value of an input element, but it's not working as expected. The code looks like this: inputT1.onblur = function () { var pDomain = this.value; $.get("netutil/php/trial500.php", { ...

Exploring the isolated scopes of AngularJS directives

Exploring directives in AngularJS led me to this interesting code snippet: var app = angular.module('app', []); //custom directive creation app.directive("myDir", function () { return { restrict: "E", scope: { title: '@ ...

Checkbox column within GridView allows users to select multiple items at once. To ensure only one item is selected at a

Currently, I am facing a challenge with dynamically binding a typed list to a GridView control within an asp.net page that is wrapped in an asp:UpdatePanel for Ajax functionality. One of the main requirements is that only one checkbox in the first column c ...

Coloring vertices in a Three.js geometry: A guide to assigning vibrant hues

This inquiry was previously addressed in this thread: Threejs: assign different colors to each vertex in a geometry. However, since that discussion is dated, the solutions provided may not be applicable to current versions of three.js. The latest versions ...

Unlocking the Potential of External Values in Angular Beyond http.then

Here is an example of my controller code: var app = angular.module('myApp'); app.controller('myCtrl', function() { $scope.year = "1350"; $scope.ord1 = ""; $scope.s1t1 = function() { $http({ url: 's1 ...

What is the best way to incorporate and organize the templateHyper folder within an established web project directory?

Can anyone offer advice on how to properly integrate and organize the 'templateHyper' (Bootstrap template) folder within my web project? I've been developing a project using C#, JavaScript, HTML, and Bootstrap's templateHyper. I'm ...

The issue arises with Datatables not functioning properly when attempting to load a specific page using

I've set up my page with datatables, you can see an example in this picture https://i.sstatic.net/p8o5S.png However, I encountered an issue when activating or deactivating my staff - the datatables search and sort functionality disappears. I believe ...

Reformatting function transforms the structure of an array containing objects

I have been struggling with certain issues and would like to find the most effective solution. Despite using map and reduce, I have not been able to achieve the desired results. Any help would be greatly appreciated. Consider the following INPUT Array str ...

error": "Unable to access undefined properties (reading 'SecretString')

Encountering the error message Cannot read properties of undefined (reading 'SecretString') when utilizing @aws-sdk/client-secrets-manager? It's a sign that you should consider updating your code to accommodate the latest version. ...

Trouble with MailChimp AJAX API not initializing the API call

I am currently working on integrating the MailChimp API to enable seamless subscription without redirecting to the MailChimp website. I found a helpful tutorial that I am following. However, whenever I attempt to subscribe, the website displays an error me ...

Where should data processing be conducted: in the service or controller layer?

Here's a question regarding the best practices for organizing code. I'm fetching data from an API using $resource and I need to manipulate it before displaying it on the view. My dilemma is at which stage should I process the data? My current b ...

Is it feasible to activate an action on a click of a Vimeo video?

Is there a way to activate an event by clicking if a video is set with background=1 and has no controls? This particular video is from Vimeo, using a plus account which allows for setting background=1. The scenario involves a Vimeo video playing on loop ...

Having trouble with $location.path() not working when trying to redirect from a .then in a factory method

I've been struggling to make my redirect work from my factory no matter what I do. I even tried moving it to the controller but it keeps throwing an error: TypeError: Cannot read property 'model.Email' of undefined The post request seems su ...

Using JQuery within Angular 4 is a valuable tool for enhancing the functionality

As a newcomer to Angular, I am experimenting with using jQuery alongside Angular 4. In my search for information, I stumbled upon this question on Stack Overflow. Inside the question, there was an example provided that can be found here. However, when att ...

Retrieve an item from a mapped array

Currently, I am using the following code snippet console.log('errors: ' + password.get('errors')); to check the output from password.get('errors'));, and in the console, the response is as follows: List [ Map { "id": "validat ...

Display a dropdown menu depending on the chosen item

In my creation of a simple dropdown list for operators, I have been contemplating whether there is a method to display dropdown items based on the selection made. For example, if I choose "Price" in the Category dropdown which requires an integer value, th ...

How can I configure the domain in a Localstorage offline JS app to access local storage from multiple HTML files?

For a small JS/HTML app I am developing, I need to store preferences in LocalStorage and access them from two different HTML files. While it works fine when staying on the same HTML file, accessing the stored data from another HTML page poses a challenge. ...

Enhanced jQuery implementation for hiding elements

I encountered a peculiar issue where jQuery's .is(':hidden') function wrongly returned true for an element that visibly displayed content. You can see the problem demonstrated in this fiddle. The :hidden pseudo checks both offsetWidth and o ...