Js Callback 运行时错误

Wrong runtime with Js Callback

我在尝试实现回调时遇到问题,希望你能帮助我。

这是我的 html:

<a class="btn btn-primary btn-xs address-pager" ng-disabled="citizensCtrl.addressIndex==citizensCtrl.citizen.addresses.length-1" ng-click="citizensCtrl.nextAddress()">
  <span class="glyphicon glyphicon-chevron-right"></span> 
</a>

ng-click中的函数是:

self.nextAddressIndexCallBack = function(){
  console.log('d');
  self.addressIndex = self.addressIndex+1;
};

self.nextAddress = function(){
  if(self.citizen.addresses[self.addressIndex].district){
    self.getAddresses(false);
    self.getZipCodes(self.nextAddressIndexCallBack());
  }
};

在函数 getZipCodes 中我发现了我的问题:

self.getZipCodes = function(callback){
  if(self.citizen.addresses[self.addressIndex].public_place.id){
    $http.get(apiUrl + "/addresses/" + self.citizen.addresses[self.addressIndex].public_place.id + "/zip_codes").then(function(response){
      console.log('a');
      self.zip_codes[self.addressIndex] = response.data;
      console.log('b');
      if(callback){
        callback;
      }
    });
  }
};

因此,我预期的正确运行时间是控制台 (a,b,d)。但这是安慰(d,a,b)。

这是实现回调的最佳方式?我如何做到同步并仅在调用 getZipCodes 函数时才执行?

你传递的函数self.nextAddressIndexCallBack()因为括号被执行了。

只需删除括号,这样您就可以在不执行回调的情况下传递它。

self.getZipCodes(self.nextAddressIndexCallBack);

顺便说一句,这类似于 question

self.nextAddressIndexCallBack() 导致函数执行,并将结果传递给调用函数..

你能试试下面的改变吗:

self.nextAddress = function(){
  if(self.citizen.addresses[self.addressIndex].district){
    self.getAddresses(false);
    //self.getZipCodes(self.nextAddressIndexCallBack());
    self.getZipCodes(self.nextAddressIndexCallBack);
  }
};

self.getZipCodes = function(callback){
  if(self.citizen.addresses[self.addressIndex].public_place.id){
    $http.get(apiUrl + "/addresses/" + self.citizen.addresses[self.addressIndex].public_place.id + "/zip_codes").then(function(response){
      console.log('a');
      self.zip_codes[self.addressIndex] = response.data;
      console.log('b');
      if(callback){
        //callback();
        callback();
      }
    });
  }
};