我正在尝试实施一个回调问题,希望你能帮助我。
这是我的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函数上调用它才能执行?
答案 0 :(得分:1)
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();
}
});
}
};
答案 1 :(得分:0)
由于括号,您执行的函数<!DOCTYPE html>
<html>
<body onload="alert('done')">
Put your spinner here.
Some text here is necessary here for the browser to start displaying.
Otherwise it will wait until it receives enough of a response to begin displaying anything.
I am not sure how much is necessary. This works for me.
<%
out.print("<br/>Starting processing now. <br/>");
out.flush();
Thread.sleep(2000);
out.print("<br/>Processing..... <br/>");
out.flush();
for(int x = 1; x < 4; x++){
Thread.sleep(2000);
out.print("Result " + x + ".<br/>");
out.flush();
}
%>
</body>
</html>
已执行。
只需删除括号,这样就可以在不执行回调的情况下传递回调。
select '{' || array_to_string(array[1,2.1,3.2,8.1,9.0], ' ') || '}';
?column?
---------------------
{1 2.1 3.2 8.1 9.0}
顺便说一句,这与此question类似。