2
我正在使用AngularJS应用程序。我有一个表格。提交时,我正在调用一个函数。我已经使用的JavaScript 的try/catch/finally块Javascript - 最终在尝试完成之前执行AngularJS块
$scope.save = function() {
try {
//Block of code to try
$scope.submit.text = "Submitting";
$scope.submit.disable = true;
$timeout(function(){
alert('successfully saved');
}, 5000);
}
catch(err) {
//Block of code to handle errors
}
finally {
alert("finally");
$scope.submit.text = "Submit";
$scope.submit.disable = false;
}
}
我用一个定时器现在。但后来我可能会使用AJAX调用。问题是
finally块在时间结束前被执行。如何解决这个问题?
你需要移动你的try catch finally块在timeout函数中,因为timeout函数是异步的。 – nikhil
请查看:http://know.cujojs.com/tutorials/async/mastering-async-error-handling-with-promises – franciscod
您也可以将任何异步函数调用转换为'kriskowal q'-like promise对象,它在AngularJS中广泛使用,名为'$ q'。 – mostruash