Every time I loop, the index of AngularJS/Ajax is being altered

My code involves creating an array from 2 ajax requests.

var myId = 13;

var array = [];

var checkIFfollowing = function(id, username){

UserService.checkIfFollowing(id, myId)
  .success(function (data) {        
    var post = {
      is_following : data, //boolean
      username : username
    }

   array.push(post);
          }).
        error(function(error) {
        //error
      });
}

UserService.GetUserById(user_id)
  .success(function (data) { 
     angular.forEach(data, function(post){    
     checkIfFollowing(post.id, post.username)
           })
          }).
        error(function(error) {
        //error
      });

The structure of the returned data is always consistent:

[{id:1, username:'ed'},{id:2, username:'joe'},{id:3, username:'bob'}]

However, after the loop, sometimes the indexes change and become inconsistent. Is there a way to ensure they remain consistent all the time?

Answer №1

The second function UserService.checkIffollowing() retrieves results asynchronously, causing the array population order to change. To address this issue, it is recommended to maintain an index and sort the array based on this index after all items have been processed. See a sample code snippet below:

var myId = 13;
var array = [];
var dataLength;

var checkIFfollowing = function (index, id, username) {
    UserAuthService.verifyFollowing(id, myId)
      .success(function (data) {
          var post = {
              followingStatus: data,
              username: username,
              index: index
          }

          array.push(post);
          if (dataLength - 1 === index) {
              array.sort(function (a, b) { return a.index - b.index })
          }
      }).error(function (error) {
          // Handle error
      });
}

UserAuthService.fetchUserById(user_id)
  .success(function (data) {
      dataLength = data.length;
      data.forEach(function (post, index) {
          checkIfFollowing(index, post.id, post.username)
      })
  }).error(function (error) {
      // Handle error
  });

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

Is it possible to invoke a code behind method from the window's onbeforeunload event

Is there a way to call a code behind method (such as saving data to a database) from window.onbeforeunload? I am unable to use PageMethods due to non-shared members like textboxes and comboboxes being present in the save method. How can I manage this scena ...

The retrieval of JSON file using $.GetJson() is unsuccessful from local directory

There is a basic autocomplete program in place. The data entered in the textbox is successfully captured while debugging, however, the GetJson() function fails to retrieve the JSON file, causing the program to malfunction. Here's the relevant code sn ...

What are some alternative ways to redirect multiple pages in a Navbar component in React Js without encountering the 'useNavigate()' error?

How can I resolve this error while working with react js? Error: useNavigate() is only allowed within a <Router> component. ▶ 3 stack frames were collapsed. Navbar C:/Users/dell/OneDrive/Desktop/ReactJs/react-learning/src/components/Navbar.js:9 ...

Interactive front end design for decision trees

On the front end, I aim to enable users to influence the outcome of a Decision Tree based on their selections. For my Django-React App, I have adopted the style and tree example from the codeplayer. You can find it here: I am tasked with creating an unor ...

Below are the steps to handle incorrect input after receiving only one letter:

H-I This is my input .centered-name { width: 80%; margin: auto; } .group { width: 100%; overflow: hidden; position: relative; } .label { position: absolute; top: 40px; color: #666666; font: 400 26px Roboto; cursor: text; transit ...

Conditional styling in React class components depending on the props provided

Dealing with older versions of material-ui that cannot be updated. I'm attempting to modify the background of the Paper component based on various prop combinations without relying on the makeStyles HOC. Is this achievable? The issue seems to lie in ...

Error encountered while testing karma: subscription function is not recognized

I encountered an issue with my karma unit test failing with the following error message. "this.gridApi.getScaleWidth().subscribe is not a function" GridApi.ts export class GridApi { private scaleWidthSubject = new BehaviorSubject<{value: number}& ...

In the event that a script encounters an error, NPM should proceed with executing any remaining

Within my package.json file, I have a script that I run using the command npm run protractor: "scripts": { "postinstall": "bower install", "pretest": "npm install", "test": "karma start test/karma.conf.js", "test-single-run": "karma start ...

Unable to locate module in Vue.js when using browserify

When trying to use almost every npm package with vue.js 1.0, I keep encountering this frustrating error: { Error: Cannot find module '!!./../../../node_modules/css-loader/index.js!./../../../node_modules/vue-loader/lib/style-rewriter.js!./../../../no ...

Troubleshooting Spring MVC and AJAX issues

Within my JSP file, there is a field where the student's group can be entered and then this data needs to be passed to the entity class GroupStudent (without using getter and setter methods). @Entity @Table(name = "GroupStudent") @NamedQueries({ @Na ...

Getting the WebElement object by manually clicking an element while in an active WebDriver Session

I am currently developing a Java Swing application for managing object repositories in Selenium scripts. This application will launch a WebDriver instance and allow users to manually navigate to the desired element for inspection. My goal is to capture th ...

Creating a custom directive in AngularJS to validate input values

I created a custom HTML form with the following structure: <div class="row col-lg-offset-3"> <div class="form-group col-lg-6" ng-class="{ 'has-error': userForm.Age.$invalid && userForm.Age.$dirty}" show-errors > & ...

Guide on generating a 2D array from linear information

Currently facing an issue while attempting to create a 5x5 grid of values. This is the structure of my code at the moment: public class a { public static void main(String[] args) { int[][] arr ={ { 9, 15, 4, 10, 7, 26, 30, 18, 24, 21, 32, 39, 42, 37, ...

"Exploring the Latest Features of NextJS 13: Enhancing Server

Currently, I am in the process of familiarizing myself with NextJS 13 and its new APP folder structure. I am facing a challenge in updating data on server components without needing to reload the page or the app. My HomePage server component fetches a list ...

How can I effectively enable the close button on the NbAlertComponent to dismiss an alert?

I have been utilizing the nebular framework in my project and I am struggling to figure out how to make the close button of the NbAlertComponent actually close the alert. When I say close, I mean stop displaying the alert after clicking on the close button ...

Incorporate properties into a component using the setup() function in Ionic and Vue framework

I am facing a challenge with passing props to a component within the <ion-nav> element. I came across this helpful tutorial for using <ion-nav>: This is how my current code looks like: <template> <div> <ion-nav :root=" ...

Error: Unable to Locate the jqueryFileTree Connector Script

I am currently working on a project to build a webpage that showcases a file tree. The jqueryFileTree plugin from the following site has been selected for this purpose: My plan is to eventually connect this tree to a server. But for now, my focus is on ge ...

integrating an array into MongoDB using Angular and NodeJS

Encountering an issue with mlab (mongoose), angular.js, HTML, and JavaScript. When passing an array with values from an angular.js controller to the server side (node.js), it fails to insert the data into the schema in mlab. Below is my HTML code: <fo ...

Is there a way to include a URL as a parameter in the router.get() function?

I am facing an issue with passing a URL http://localhost:3000/new/https://www.example.com as a parameter to router.get('/new/:url', function..). Instead of receiving the desired url (https://www.example.com) in req.params.url, I am encountering a ...

Error: An unexpected 'if' token was not caught

Encountering an error related to the question title while working with this code snippet: $LAB.queue(function setup() { FB.init({ appId: '00000000', status: true, cookie: true, xfbml: true, logging: &ap ...