简体   繁体   English

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

[英]In angular function not waiting to complete first function execution

my function didnt wait to complete earlier function execution and it is completing. 我的函数没有等到完成早期的函数执行,它正在完成。

I have my code is that i am doing some thing wrong: 我有我的代码是我做错了一些事情:

$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){

            });
   };

so in this it is not waiting to get address instead of it moving down so how to wait finishing for loop and then call different function. 所以在这里它不是等待获取地址而不是它向下移动所以如何等待完成循环然后调用不同的功能。 createBody function called before the $scope.xyz() function returns the value how to wait until loop finishes 在$ scope.xyz()函数之前调用的createBody函数返回如何等待循环结束的值

This is expected due to asynchronous nature of execution. 由于执行的异步性质,这是预期的。 You should use callbacks to avoid this problem. 您应该使用回调来避免此问题。

You should use the $q service. 您应该使用$q服务。
first store all $http calls in an array and with $q.all(array) you create a promise that is resolved after all $http promises have resolved. 首先将所有$http调用存储在一个数组中,并使用$q.all(array)创建一个在所有$http promises已解决后解析的promise。

eg: 例如:

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

};

And on the resolve of this new promise you can call your createBody function. 在这个新承诺的决心你可以调用你的createBody函数。

For this to work You should also change success callback on the $scope.xyz to a then callback and return the promise. 为此,您还应该将$scope.xyz上的success回调更改为then回调并返回promise。

eg: 例如:

$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){

  });
};

UPDATE UPDATE

If you don't care if all calls succeed, replace: 如果您不关心所有呼叫是否成功,请替换:

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

With: 附:

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

PS: Keep in mind that in the finally callback you don't get the return values of every call, whereas in the then an array will be passed as argument in the callback function which holds in every position a return value of each $http call. PS:请记住,在finally回调中你没有得到每个调用的返回值,而在then一个数组将作为参数传递给回调函数,该函数在每个位置保存每个$http调用的返回值。

There are two way to achieve this 实现这一目标有两种方法

1)Use async:false 1)使用async:false

2)Need to use callback 2)需要使用回调

choose your way and enjoy! 选择你的方式,享受!

You should how promises works in javascript. 你应该如何在javascript中使用promises。

$http is an asynchronous function. $ http是一个异步函数。 You must return $http result in $scope.xyz function and use then, success, error function callbacks. 您必须在$ scope.xyz函数中返回$ http结果并使用then,success,error函数回调。

Example: 例:

function xyz() {
   return $http(...);
}

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

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

hope this helps! 希望这可以帮助! regards 问候

You can use Angular promises. 您可以使用Angular承诺。

Include promise status to self created object with deferred value, that has valueOf and toString methods. 将promise状态包含到具有延迟值的自创建对象,具有valueOftoString方法。 Last two methods allow to use arithmetic, string and comparison operators. 最后两种方法允许使用算术,字符串和比较运算符。

Object with deferred value: 具有延迟值的对象:

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

Return this object in your ASYNC function, and resolve them after retrieving data: 在ASYNC函数中返回此对象,并在检索数据后解析它们:

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

Plunker example Plunker的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM