SyncPromise.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. /* ------------------------------------------------------------------------ */
  3. module.exports = class SyncPromise {
  4. constructor (fn) {
  5. try {
  6. fn (
  7. x => { this.setValue (x, false) }, // resolve
  8. x => { this.setValue (x, true) } // reject
  9. )
  10. } catch (e) {
  11. this.setValue (e, true)
  12. }
  13. }
  14. setValue (x, rejected) {
  15. this.val = (x instanceof SyncPromise) ? x.val : x
  16. this.rejected = rejected || ((x instanceof SyncPromise) ? x.rejected : false)
  17. }
  18. static valueFrom (x) {
  19. if (x instanceof SyncPromise) {
  20. if (x.rejected) throw x.val
  21. else return x.val
  22. } else {
  23. return x
  24. }
  25. }
  26. then (fn) {
  27. try { if (!this.rejected) return SyncPromise.resolve (fn (this.val)) }
  28. catch (e) { return SyncPromise.reject (e) }
  29. return this
  30. }
  31. catch (fn) {
  32. try { if (this.rejected) return SyncPromise.resolve (fn (this.val)) }
  33. catch (e) { return SyncPromise.reject (e) }
  34. return this
  35. }
  36. static resolve (x) {
  37. return new SyncPromise (resolve => { resolve (x) })
  38. }
  39. static reject (x) {
  40. return new SyncPromise ((_, reject) => { reject (x) })
  41. }
  42. }