execute.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * This file is part of Threema Web.
  3. *
  4. * Threema Web is free software: you can redistribute it and/or modify it
  5. * under the terms of the GNU Affero General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or (at
  7. * your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Affero General Public License
  15. * along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * Execute a promise and wait x (timeout) seconds for end the process
  19. * Used for a better user experience on saving forms
  20. */
  21. export class ExecuteService {
  22. private $log: ng.ILogService;
  23. private $timeoutService: ng.ITimeoutService;
  24. private timeout: number;
  25. private started = false;
  26. public static $inject = ['$log', '$timeout'];
  27. constructor($log: ng.ILogService, $timeout: ng.ITimeoutService, timeout = 0) {
  28. // Angular services
  29. this.$log = $log;
  30. this.$timeoutService = $timeout;
  31. this.timeout = timeout;
  32. }
  33. public execute(runnable: Promise<any>): Promise<any> {
  34. if (this.started) {
  35. this.$log.error('execute already in progress');
  36. return null;
  37. }
  38. this.started = true;
  39. return new Promise((a, e) => {
  40. runnable
  41. .then((arg: any) => {
  42. this.$timeoutService(() => {
  43. this.started = false;
  44. a(arg);
  45. }, this.timeout);
  46. })
  47. .catch((arg: any) => {
  48. this.started = false;
  49. e(arg);
  50. });
  51. });
  52. }
  53. public isRunning(): boolean {
  54. return this.started;
  55. }
  56. }