如何始终运行约code当一个承诺在Angular.js得到满足 [英] How to always run some code when a promise is fulfilled in Angular.js
问题描述
在我Angular.js的应用程序,我跑了一些异步操作。它开始我盖上模态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
})
它工作得很好,不过,我想preFER有清洁的东西像这样的伪code:
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();
})
我以为这是一个相当普遍的问题,所以我想这是可以做到,但无法找到在doc什么。任何想法,如果这是可以做到?
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?
推荐答案
该功能已在实施这个要求拉现在是AngularJS的一部分。它最初是一个名为总是
再后来更名为最后
,所以code应该如下:
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
});
请注意,由于最后
是保留关键字,可能有必要使它成为一个字符串:
Note that since finally
is a reserved keyword, it might be necessary to make it a string:
$http.get('/foo')['finally'](doSomething);
这篇关于如何始终运行约code当一个承诺在Angular.js得到满足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!