AngularJS: iterating through POST requests and passing each index into its corresponding response

Using AngularJS, I am attempting to execute multiple http POST requests and create an object of successfully finished requests. Here is a sample code snippet:

var params = [1, 2, 3],
    url,
    i,
    done = {};

for (i in params) {
    url = '/dir/'+ params[i];
    $http.post(url, {"some_request": "not important"}).
        success(function(response) {
            done[params[i]] = 'successful';
        });
}

The desired outcome is an object containing all successful requests like this:

done = {1: 'successful', 2: 'successful', 3: 'successful'};

However, due to the asynchronous nature of http requests, only the last successful request is captured:

done = {3: 'successful'};

Since the loop finishes before the responses are returned, how can the loop index be passed into the responses? Your help is appreciated.

Answer №1

Here's a solution that may work:

var values = [1, 2, 3],
    url,
    index,
    finished = {};

for (index in values) {
    (function(val) {
        url = '/directory/'+ values[val];
        $http.post(url, {"some_request": "not critical"}).
            success(function(response) {
                finished[values[val]] = 'completed';
            });
    })(index);
}

You could also consider using closure as another approach.

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

Triggering jQuery events can be customized by excluding certain elements using the

Is there a way to hide the div "popu" when clicking on the img "tri"? I've tried using .not() since the img is a child of the div popu, but it didn't work. Also, I need to make sure that clicking on the div "textb" does not trigger the hide actio ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

Node development does not operate continuously

I'm facing a minor issue with node-dev. I followed the instructions in the readme file and successfully installed it. However, when I run the command like so: node-dev somescript.js, it only runs once as if I used regular node without -dev. It doesn&a ...

The Cascading of Bootstrap Card Designs

Looking for some assistance with my TV Show Searcher project that is based on an API. The functionality is complete, but I'm struggling to get the Bootstrap cards to stack neatly without any empty space between them. I want it to resemble the image ga ...

Is there a way to update the background image of a div element through a JavaScript file within a react component?

After spending hours on this issue, I am still stuck and have exhausted all my ideas and research. In my project, I have three buttons that are supposed to change the background image of my site. The background image is linked to the default "App" div elem ...

The Keydown Event in Asp.net GridView may sometimes fail to be triggered

While working within a gridview on Internet Explorer, users can click on cells in one column to reveal a hidden textbox. After entering text into the textbox, users are instructed to press the Tab key to save changes. To accomplish this, a Javascript funct ...

Leveraging route configuration's scope in HTML

As a beginner in AngularJs, I am currently exploring the creation of a single page application. However, I am encountering difficulties in converting my initial code into more professional and efficient code. During this conversion process, I have separate ...

Exploring nested JSON through recursive iteration in JavaScript

Consider this JSON data containing comments that are fetched via AJAX call: json = 'comments': [ {'id':1,'parent':0}, {'id':2,'parent':1}, {'id':3,'parent':2}, {'id&apos ...

Monitor the latest website address being typed into the browser

Is it possible to track the new URL entered by a user in the browser when they leave the current page using the onunload event? For example, if a user is currently on www.xyz.com/page1.aspx and then types a new URL into the browser, I want to capture that ...

Retrieving information and implementing condition-based rendering using React's useEffect

I am currently developing a MERN stack application that retrieves information regarding college classes and presents it in a table format. The CoursesTable.js component is structured as follows: import React, { useState, useEffect } from 'react'; ...

Excellent Methods for Implementing a Double Click Functionality in JavaScript for Mouse

Is there a way to make the mouse double click by itself using JavaScript? I need this functionality for a Selenium project that requires testing, but unfortunately Selenium does not provide an option for double clicking. Can anyone suggest how I can achiev ...

Troubleshooting Cordova's ng-route functionality issue

I am currently working on an Angular application that includes the following code: // app.js var rippleApp = angular.module('rippleApp', ['ngRoute', 'ngAnimate', 'ngAria', 'ngMaterial']); // configure ou ...

The passport is experiencing an authentication issue: The subclass must override the Strategy#authenticate method

After attempting to authenticate and log in a user, I encountered an error message stating: Strategy#authenticate must be overridden by subclass. How can I resolve this issue? What could be causing this error to occur? Concerning Passport.js const LocalS ...

"Encountering a challenge when trying to populate a partial view using AngularJs and MVC

I am a beginner in AngularJS and I'm using a partial view for Create and Edit operations, but I'm encountering issues while trying to retrieve the data. The data is successfully being retrieved from my MVC controller but it's not populating ...

"Maximizing Efficiency: Chaining Several Actions Using the JavaScript Ternary Operator

When the condition is true, how can I chain two operations together? a = 96 c = 0 a > 50 ? c += 1 && console.log('passed') : console.log('try more') I attempted chaining with && and it successfully worked in react, b ...

Utilizing client-side storage within a React project

As part of my React challenge tracking app development, I am looking to implement a feature where users can click on a challenge button, approve it, and then save the chosen challenge name to local storage. Later, this saved challenge will be displayed in ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

Struggling to retrieve the accurate input value when the browser's return button is clicked?

Having multiple forms created for different conditions, each one submits to a different page. However, when I navigate back from the other page, all my forms display the same values as before. Here's the code snippet: <form action="<?php echo b ...

Is the DOMContentLoaded event connected to the creation of the DOM tree or the rendering tree?

After profiling my app, I noticed that the event is triggered after 1.5 seconds, but the first pixels appear on the screen much later. It seems like the event may only relate to DOM tree construction. However, this tutorial has left me feeling slightly con ...

What could be causing the images' load event not to work as expected?

I'm attempting to implement a load event for my images using native JavaScript. Below is the code snippet I am currently using: var imgs = $("figure img"); // querySelectorAll for(var i = 0, l = imgs.length ; i < l ; ++i) imgs[i].addEventListen ...