Created
January 8, 2018 14:22
-
-
Save EfraimB/918eebdf7dd020801c72da1289c8d797 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PromiseCancelledError: CancellableError { | |
var isCancelled: Bool { | |
return true | |
} | |
} | |
public class CancelablePromise<T> { | |
var promise:Promise<T> | |
var cancellable:TTCancellable! | |
var reject:((Error) -> Void)! | |
init(resolvers: (_ fulfill: @escaping (T) -> Void, _ reject: @escaping (Error) -> Void) throws -> Void, cancellable:TTCancellable) { | |
var _reject:((Error) -> Void)! | |
self.promise = Promise<T> { (fulfill, reject) in | |
_reject = reject | |
try? resolvers(fulfill,reject) | |
} | |
self.reject = _reject | |
self.cancellable = cancellable | |
} | |
init(promise:Promise<T>, cancellable:TTCancellable ) { | |
self.promise = promise | |
self.cancellable = cancellable | |
} | |
public func cancel() { | |
guard promise.isPending else { | |
return | |
} | |
reject(PromiseCancelledError()) | |
cancellable.cancel() | |
} | |
var value:T? { | |
return promise.value | |
} | |
@discardableResult | |
public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> U) -> Promise<U> { | |
return promise.then(on: q, execute: body) | |
} | |
@discardableResult | |
public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> Promise<U>) -> Promise<U> { | |
return promise.then(on: q, execute: body) | |
} | |
@discardableResult | |
public func `catch`(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) -> Void) -> Promise<T> { | |
return promise.catch(on: q, policy: policy, execute: body) | |
} | |
public func `catch`(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) -> Void) { | |
_ = promise.catch(on: q, policy: policy, execute: body) | |
} | |
@discardableResult | |
public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> Promise<T>) -> Promise<T> { | |
return promise.recover(on: q, policy: policy, execute: body) | |
} | |
@discardableResult | |
public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> T) -> Promise<T> { | |
return promise.recover(on: q, policy: policy, execute: body) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great thanks.