在角度函数中不等待完成第一个函数执行

In angular function not waiting to complete first function execution

本文关键字:函数 第一个 执行 等待      更新时间:2023-09-26

我的函数没有等待完成早期的函数执行,它正在完成。

我的代码是我做错了一些事情:

$scope.abc1 = function(){
 var arrayJson = [{'name':'max','age':'12'},{'name':'tax','age':'16'}]
 for(var i=0; i<arratJson.length;i++){
  var getAddress = $scope.xyz(arratJson[i].name);
    }
  $scope.createBody();
 };
 $scope.createBody = function(){
 //some more code here
 };
 $scope.xyz = function(name){
    $http({
            method: 'GET',
            url: 'rest/address',
            type:'json',
            headers:{'action':'single','name':name},  
            }).success(function(response){
             return response;
            }).error(function(response){
            });
   };
所以

在这里它不是等待获取地址而不是向下移动,所以如何等待完成循环,然后调用不同的函数。在 $scope.xyz() 函数之前调用的 createBody 函数返回值如何等待循环完成

由于执行的异步性质,这是意料之中的。您应该使用回调来避免此问题。

您应该使用 $q 服务。
首先将所有$http调用存储在数组中,然后使用 $q.all(array)创建一个承诺,该承诺在所有承诺都已解析后解析$http

例如:

$scope.abc1 = function(){
  var arrayJson = [{'name':'max','age':'12'},{'name':'tax','age':'16'}]
  var promises = [];
  for(var i=0; i<arratJson.length;i++){
    promises.push($scope.xyz(arratJson[i].name));
  }
  $q.all(promises).then($scope.createBody);
};

在这个新承诺的决心下,你可以调用你的createBody函数。

为此,您还应该将$scope.xyz上的回调更改为then回调success并返回 promise。

例如:

$scope.xyz = function(name){
  return $http({
    method: 'GET',
    url: 'rest/address',
    type:'json',
    headers:{'action':'single','name':name},  
  }).then(function(response){
    return response;
  })["catch"](function(response){
  });
};

更新

如果您不在乎所有调用是否成功,请替换:

$q.all(promises).then($scope.createBody);

跟:

$q.all(promises)["finally"]($scope.createBody);

PS:请记住,在finally回调中,您不会获得每个调用的返回值,而在then中,数组将作为参数在回调函数中传递,该函数在每个位置保存每个$http调用的返回值。

有两种方法可以实现这一点

1)使用 async:false

2)需要使用回调

选择你的方式,享受!

你应该如何在 javascript 中 promise 工作。

$http是一个异步函数。您必须返回 $http 结果 $scope.xyz 函数,然后使用成功、错误函数回调。

例:

function xyz() {
   return $http(...);
}
xyz().then(function(data) {
    address = data.data.address; // in your json dto format
})

更多信息 https://docs.angularjs.org/api/ng/service/$http

希望这有帮助!regards

你可以使用 Angular 承诺。

将承诺状态包含在具有延迟值的自创建对象中,该对象具有valueOftoString方法。最后两种方法允许使用算术、字符串和比较运算符。

具有递延值的对象:

 var DeferredValue = function(initial){
    var self = this;
    self._value = initial; 
    var deferred = $q.defer();
    self.$promise = deferred.promise;
    self.$resolved = false;
    self.$resolve = function(value){
      deferred.resolve(value);
    }
    self.$promise.then(function(v){
      self._value = v;
      deferred = null;
      self.$resolved = true;
      delete self.$resolve;
      return self.$promise;
    });
  }
  DeferredValue.prototype = {
    constructor: DeferredValue,
    valueOf: function(){
      return this._value
    },
    toString: function(){
      return this._value.toString()
    }
  }

在 ASYNC 函数中返回此对象,并在检索数据后解析它们:

var getValue = function(){
  var value = new DeferredValue();
  $timeout(function(){
    value.$resolve(Math.floor(Math.random() * 10))
  },1500);
  return value;
}

普伦克示例