Last active
October 19, 2021 19:00
-
-
Save elmodos/01e7b4b666d9b0280cb339457dab9e9d to your computer and use it in GitHub Desktop.
Quick promise implemention
This file contains hidden or 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
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