Deferred.bak.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * @Author: Rindy
  3. * @Date: 2021-08-13 12:00:10
  4. * @LastEditors: Rindy
  5. * @LastEditTime: 2021-08-13 15:32:02
  6. * @Description: 兼容jQuery.Deferred :(
  7. */
  8. const noop = function () {}
  9. Promise.prototype.done = Promise.prototype.then
  10. Promise.prototype.fail = Promise.prototype.catch
  11. class Deferred {
  12. constructor() {
  13. this._resolve = []
  14. this._reject = noop
  15. this._notify = noop
  16. this._progress = noop
  17. this._state = 'pending'
  18. }
  19. state() {
  20. return this._state
  21. }
  22. done(resolve) {
  23. this._resolve.push(resolve)
  24. return this
  25. }
  26. fail(reject) {
  27. this._reject = reject
  28. return this
  29. }
  30. then(resolve) {
  31. this._resolve.push(resolve)
  32. return this
  33. }
  34. catch(reject) {
  35. this._reject = reject
  36. return this
  37. }
  38. notify(...args) {
  39. this._notify = [...args]
  40. if (typeof this._progress == 'function') {
  41. this._progress.apply(null, this._notify)
  42. }
  43. return this
  44. }
  45. when(...args) {
  46. Promise.all([...args])
  47. .then((...args) => {
  48. this._state = 'resolve'
  49. this._resolve.forEach(item => item(...args))
  50. })
  51. .catch((...args) => {
  52. this._state = 'reject'
  53. this._reject(...args)
  54. })
  55. }
  56. progress(callback) {
  57. this._progress = callback
  58. return this
  59. }
  60. resolve(result) {
  61. this._state = 'resolve'
  62. return Promise.resolve().then(() => this._resolve.forEach(item => item(result)))
  63. }
  64. reject(result) {
  65. this._state = 'reject'
  66. return Promise.reject().catch(() => this._reject(result))
  67. }
  68. promise() {
  69. return this
  70. }
  71. }
  72. export default function () {
  73. return new Deferred()
  74. }