Guest User

Untitled

a guest
Jan 16th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. class PromiseCancelledError: CancellableError {
  2. var isCancelled: Bool {
  3. return true
  4. }
  5. }
  6.  
  7. public class CancelablePromise<T> {
  8.  
  9. var promise:Promise<T>
  10. var cancellable:TTCancellable!
  11. var reject:((Error) -> Void)!
  12.  
  13.  
  14. init(resolvers: (_ fulfill: @escaping (T) -> Void, _ reject: @escaping (Error) -> Void) throws -> Void, cancellable:TTCancellable) {
  15.  
  16. var _reject:((Error) -> Void)!
  17. self.promise = Promise<T> { (fulfill, reject) in
  18. _reject = reject
  19. try? resolvers(fulfill,reject)
  20. }
  21. self.reject = _reject
  22. self.cancellable = cancellable
  23.  
  24. }
  25.  
  26. init(promise:Promise<T>, cancellable:TTCancellable ) {
  27. self.promise = promise
  28. self.cancellable = cancellable
  29. }
  30.  
  31.  
  32. public func cancel() {
  33. guard promise.isPending else {
  34. return
  35. }
  36. reject(PromiseCancelledError())
  37. cancellable.cancel()
  38. }
  39.  
  40. var value:T? {
  41. return promise.value
  42. }
  43.  
  44. @discardableResult
  45. public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> U) -> Promise<U> {
  46. return promise.then(on: q, execute: body)
  47. }
  48.  
  49. @discardableResult
  50. public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> Promise<U>) -> Promise<U> {
  51. return promise.then(on: q, execute: body)
  52. }
  53.  
  54. @discardableResult
  55. public func `catch`(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) -> Void) -> Promise<T> {
  56. return promise.catch(on: q, policy: policy, execute: body)
  57. }
  58.  
  59. public func `catch`(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) -> Void) {
  60. _ = promise.catch(on: q, policy: policy, execute: body)
  61. }
  62.  
  63. @discardableResult
  64. public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> Promise<T>) -> Promise<T> {
  65. return promise.recover(on: q, policy: policy, execute: body)
  66. }
  67.  
  68. @discardableResult
  69. public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> T) -> Promise<T> {
  70. return promise.recover(on: q, policy: policy, execute: body)
  71. }
  72.  
  73. }
Add Comment
Please, Sign In to add comment