future.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. /**
  3. * A future similar to Python's asyncio.Future. Allows to resolve or reject
  4. * outside of the executor and query the current status.
  5. */
  6. class Future extends Promise {
  7. constructor(executor) {
  8. let resolve, reject;
  9. super((resolve_, reject_) => {
  10. resolve = resolve_;
  11. reject = reject_;
  12. if (executor) {
  13. return executor(resolve_, reject_);
  14. }
  15. });
  16. this._done = false;
  17. this._resolve = resolve;
  18. this._reject = reject;
  19. }
  20. /**
  21. * Wrap a promise to ensure it does not resolve before a minimum
  22. * duration.
  23. *
  24. * Note: The promise will still reject immediately. Furthermore, be
  25. * aware that the promise does not resolve/reject inside of
  26. * an AngularJS digest cycle.
  27. *
  28. * @param promise the promise or future to be wrapped
  29. * @param minDuration the minimum duration before it should be resolved
  30. * @returns {Future}
  31. */
  32. static withMinDuration(promise, minDuration) {
  33. const start = new Date();
  34. return new Future((resolve, reject) => {
  35. promise
  36. .then((result) => {
  37. const timediff = new Date() - start;
  38. const delay = Math.max(minDuration - timediff, 0);
  39. self.setTimeout(() => resolve(result), delay);
  40. })
  41. .catch((error) => reject(error));
  42. });
  43. }
  44. /**
  45. * Return whether the future is done (resolved or rejected).
  46. */
  47. get done() {
  48. return this._done;
  49. }
  50. /**
  51. * Resolve the future.
  52. */
  53. resolve(...args) {
  54. this._done = true;
  55. return this._resolve(...args);
  56. }
  57. /**
  58. * Reject the future.
  59. */
  60. reject(...args) {
  61. this._done = true;
  62. return this._reject(...args);
  63. }
  64. }