问题描述
在我的 Angular.js 应用程序中,我正在运行一些异步操作.在开始之前我用模态div覆盖应用程序,然后一旦操作完成,我需要删除div,无论操作成功与否.
In my Angular.js application, I'm running some asynchronous operation. Before it starts I cover the application with a modal div, then once the operation is complete, I need to remove the div, whether the operation was successful or not.
目前我有这个:
LoadingOverlay.start();
Auth.initialize().then(function() {
LoadingOverlay.stop();
}, function() {
LoadingOverlay.stop(); // Code needs to be duplicated here
})
它运行良好,但我更喜欢像这样的伪代码更干净:
It works well, however I would prefer to have something cleaner like this pseudo-code:
LoadingOverlay.start();
Auth.initialize().finally(function() { // *pseudo-code* - some function that is always executed on both failure and success.
LoadingOverlay.stop();
})
我认为这是一个很常见的问题,所以我认为可以完成但在文档中找不到任何内容.不知道能不能实现?
I assume it's quite a common problem, so I was thinking it could be done but cannot find anything in the doc. Any idea if it can be done?
推荐答案
该功能已经在这个pull request中实现 并且现在是 AngularJS 的一部分.最初叫always",后来改名为finally
,所以代码应该如下:
The feature has been implemented in this pull request and is now part of AngularJS. It was initially called "always" and then later renamed to finally
, so the code should be as follow:
LoadingOverlay.start();
Auth.initialize().then(function() {
// Success handler
}, function() {
// Error handler
}).finally(function() {
// Always execute this on both error and success
});
请注意,由于 finally
是保留关键字,因此可能需要将其设为字符串,以免在某些浏览器(例如 IE 和 Android 浏览器)上中断:
Note that since finally
is a reserved keyword, it might be necessary to make it a string so that it doesn't break on certain browsers (such as IE and Android Browser):
$http.get('/foo')['finally'](doSomething);
这篇关于在 Angular.js 中实现承诺时如何始终运行一些代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!