当我执行循环时,AngularJs/Ajax索引正在改变

AngularJs/Ajax index is changing when i do a loop

本文关键字:索引 Ajax 改变 AngularJs 执行 循环      更新时间:2023-09-26

我有一个从2 ajax请求创建的数组。

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
      });

数据结构总是这样返回:

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

但是在循环之后索引改变了,但是很多时候它们都是相同的索引。有没有办法让它始终保持一致

第二个userservice . checkifollowing()异步返回结果,因此填充数组的顺序将发生变化。一种有效的方法是维护一个索引,并在处理完所有项后按索引对数组进行排序。示例代码如下:

var myId = 13;
var array = [];
var dataLength;
var checkIFfollowing = function (index, id, username) {
    UserService.checkIfFollowing(id, myId)
      .success(function (data) {
          var post = {
              is_following: data, //boolean
              username: username,
              index: index
          }
          array.push(post);
          if (dataLength - 1 === index) {
              array.sort(function (a, b) { return a.index - b.index })
          }
      }).error(function (error) {
          //error
      });
}
UserService.GetUserById(user_id)
  .success(function (data) {
      dataLength = data.length;
      data.forEach(function (post, index) {
          checkIfFollowing(index, post.id, post.username)
      })
  }).error(function (error) {
      //error
  });