内部循环的服务调用即使条件为假也不会停止循环

时间:2017-09-04 16:46:03

标签: angularjs foreach asynchronous-javascript

如果getModelData变为shouldPermit,我想停止重复调用true。但是下面的代码总是在控制台中为每个why I got printed forEach newlySelectedUsers打印newlySelectedUsers

var shouldPermit = false;
angular.forEach(newlySelectedUsers, function(value, key) {
if(!shouldPermit) { 
console.log("why I got printed forEach newlySelectedUsers")                         
userService.getModelData($scope.$root.test[value].id)
.success(function (data) {                                
    if(lodash.isEmpty(data)) {                                      
        shouldPermit = true;
        $scope.insertSaving();
     }
       });                           
         }                      
          });

getModelData成为真后,如何停止对shouldPermit的来电?

2 个答案:

答案 0 :(得分:0)

这是因为异步。第二次迭代不等待第一次迭代调用的// if the action doesn't exist in localStorage, set the class to "disabled" if ((lstore == null) || !(lstore.hasOwnProperty(action))) { span.classList.add("disabled"); }完成。因此,即使在第一次迭代userService.getModelData()的成功函数转换为userService.getModelData()之前,您也会收到控制台消息。

相反,您只需将shouldPermit移至顶部即可解决问题。

shouldPermit = true;

答案 1 :(得分:0)

那是因为所有http请求异步运行。有人说,你的itteration运行速度比服务查找(在你的情况下)空数据变量所需的时间要快。

选项是递归调用http请求:

const totalNewlySelectedUsers = newlySelectedUsers.length;


function getUser(idx) {

    let value = newlySelectedUsers[idx];

    userService.getModelData($scope.$root.test[value].id)
        .success(function (data) {
            if (lodash.isEmpty(data))
                $scope.insertSaving();
                return;
            }

            if(idx === totalNewlySelectedUsers) return;

            getUser(idx + 1);
        });

}

getUser(0);