Skip to content

Instantly share code, notes, and snippets.

@elmodos
Last active October 19, 2021 19:00
Show Gist options
  • Save elmodos/01e7b4b666d9b0280cb339457dab9e9d to your computer and use it in GitHub Desktop.
Save elmodos/01e7b4b666d9b0280cb339457dab9e9d to your computer and use it in GitHub Desktop.
Quick promise implemention
import Foundation
public class Promise<T> {
public private(set) lazy var future: Future<T> = Future()
public init() { /**/ }
public func fulfill(_ value: T) {
future.result = .success(value)
}
public func reject(_ error: Error) {
future.result = .failure(error)
}
}
public class Future<T> {
fileprivate var result: Result<T, Error>? { didSet { notifyHandlersIfNeeded() } }
private var handlers: [ResultHandler] = []
private let lock = NSRecursiveLock()
public typealias ResultHandler = (Result<T, Error>) -> Void
public func value(_ handler: @escaping ResultHandler) {
locked { self.handlers.append(handler) }
notifyHandlersIfNeeded()
}
private func notifyHandlersIfNeeded() {
locked {
guard let result = result else { return }
handlers.forEach { $0(result) }
handlers.removeAll()
}
}
private func locked(_ closure: () -> Void) {
lock.lock()
closure()
lock.unlock()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment