"Utilizing $http requests within Angular forEach loops prior to receiving the HTTP response

In my JavaScript code, I am working with a list called $scope.propname that contains an object named latlong. My goal is to calculate the distance of all properties from a specific location. This is the approach I have taken:

for (var i = 0; i < $scope.propname.length; i++) {
  if ($scope.propname[i].latlong == "") {
    var pptlatlong = ("" + "," + "");
  } else {
    var pptlatlong = $scope.propname[i].latlong.replace(/\s*,\s*/g, ",");
  }
  var latlongdata = {
    scoord: $scope.loclatlong,
    ecoord: pptlatlong
  }
  $http({
    method: 'post',
    data: latlongdata,
    url: $rootScope.ServiceBaseUri + 'Map/geolocation'
  }).then(function successCallback(resp) {
    $scope.latlongdist = resp.data;
  }, function errorCallback(resp) {});
  $scope.propname[i].dist = $scope.latlongdist;
}

After running this loop, I noticed that all objects named dist in the list have the same value. I believe this is because the loop continues before each HTTP response has finished. Is there a way to pause the loop until each HTTP request completes before proceeding?

Answer №1

a more efficient method,

let locationCoordinates = $scope.locationCoordinates,
    geoLocationUrl = $rootScope.ServiceBaseUri + 'Map/geolocation';

$scope.propertyList.forEach(function(property, index) {

    let propertyCoordinates = (property.coordinates === "") ? (""+","+ "") : property.coordinates.replace(/\s*,\s*/g, ",");

    let coordinatesData = {
        startCoordinates: locationCoordinates,
        endCoordinates: propertyCoordinates
    };

    $http({
        method: 'post',
        data: coordinatesData,
        url: geoLocationUrl
    })
    .then(
        function(response) {
            $scope.propertyList[index].distance = response.data;
        },
        function(error) {
            console.log(error);
        }
    );
});

Answer №2

Every operation within your for-loop is executed prior to the completion of the asynchronous call.

To address this, simply assign your values inside the .then function, like so:

$scope.propname[i].dist = response.data;

It is crucial to note: a more effective approach would involve storing all the promises in an array and accessing the propname values only after they have all been resolved. This will guarantee that no unresolved values are missed.

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

How to use jQuery to update the href attribute of a parent link

Can someone help me figure out why I am having trouble changing the 'href' of the parent link to a header logo? Thank you in advance! Here is the HTML code snippet: <a href="https://URL.IWANTO.CHANGE"> <img id="partner_logo" src="/ ...

React: Selecting Component Name Based on Provided Property

My goal is to dynamically load an icon component in React passed as a prop from the parent component. Dashboard (parent): import { Button } from './components'; function App() { return ( <div className="app"> <d ...

What is the best way to identify identical companies, consolidate them into a single entity, and combine their weights for a more

I've been experimenting with various methods such as filter, reduce, and includes, but I'm struggling to grasp the concept of how to solve this. Here is an array of objects that I have: [ { name: 'GrapeCo', weight: 0.15 }, { name: ...

Creating a simulated callback function using Jest with a promise

I am currently testing a specific function within my component that is triggered only when the API request is successful. To provide some background, this function is called upon clicking a button: return onUpdate(params, setError, success, cancel); Once ...

Contrast between utilizing i < strlen() and str[i] not equal to ''

My code used to generate a time limit exceed error when I implemented it with the syntax for(i=0;i<strlen(s);i++). However, when I changed it to for(i=0;s[i]!='\0';i++), the submission was successful. What could be the reason for this dif ...

What is the proper way to include a closing tag for the canvas in a Canvas rendered by Three.js

Why does three js always add canvas elements without a closing tag to the page? Is there a specific reason for this? I'm interested in adding a closing tag to this canvas element. This example page was inspected, revealing something similar to this ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

Node functions continue to run smoothly without affecting the loop

I am working on a webdriverjs application and I am trying to determine when jQuery has finished its processes on the page. I have implemented some methods, but it seems that even when the condition is supposed to trigger an else statement and stop the loop ...

Transform the snake code by incorporating a visual image as the face of the serpent

Can someone help me change the snake's face to an image instead of a color fill in this code? And how can I add arrows for mobile compatibility? (function() { // Insert JS code here })(); // Insert CSS code here This code snippet includes functi ...

How can we use Mongoose .find to search with an array stored in req.params and respond with an array containing each value along with its

It would be great if a user could input multiple tags in a search field, and have them separated client-side (before making the .get call) to send over ajax with each keypress. While testing the API with Postman on the server-side, if the .get method retu ...

What are the steps to activate the hot-swapping feature for HTML and JavaScript files in IntelliJ's Community edition?

Just starting out with IntelliJ to work on an AngularJS project with spring-boot as the backend server. Every time I make changes to my HTML or JavaScript code, I find myself needing to restart the app server. Is there a configuration setting or plugin ava ...

What is the best way to utilize getInitialProps specifically during the building process of a NextJS site?

When I am developing a static site using NextJS, I need the getInitialProps method to run specifically during the build process and not when the client loads the page. During the build step, NextJS executes the getInitialProps method before generating the ...

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...

Error: Cannot execute 'x' as a function

I am currently developing an Express web application that initiates JavaScript scraping code upon the page's initial load. Below is the node web scraping code (scrape.js): const request = require('request-promise'); const cheerio = require( ...

What is the method for accessing a selector within a foreach loop?

Whenever a user clicks on a date in the jquery datepicker, two ajax calls are triggered. The goal is for the second ajax call to populate the response/data into a paragraph with the class spots within the first ajax call, displaying available spots for th ...

Comparison Between Object and Array

When inputting the values {2,4,45,50} in the console, 50 is displayed. However, assigning these values to a variable results in an error: var a = {2,4,45,50} Uncaught SyntaxError: Unexpected number Can you explain this concept? ...

Retrieving JSON data from outside the React root directory

My current project includes an older javascript/php application with numerous JSON files used to retrieve data from the database. As I plan to migrate some modules to React, I am wondering if it's possible to still fetch data from these JSON files wi ...

Choose a navigation item from the list containing a nested span element

I've implemented selectnav from GitHub and it's functioning perfectly. However, my menu consists of list items with a description span inside each one, resulting in menu items structured as shown below: <li><a href="somelink.html">Ch ...

The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them: List of Playlists: export default class Playlists extends Component { playlists = [ ... ]; render() { const {navigation} = th ...

The error occurs when Facebook and Twitter iframes are attempting to access and set 'document.domain'

When attempting to add Tweet and Facebook Like buttons to the project I'm working on, everything appears to be functioning properly. However, upon clicking the buttons, a JavaScript error occurs: Unsafe JavaScript attempt to access frame with URL htt ...