Created
June 30, 2015 01:01
-
-
Save atomkirk/7d9c902782f6d1a7e04a to your computer and use it in GitHub Desktop.
Simple Promise implementation
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
import Foundation | |
public class Promise<T> { | |
public typealias PromiseSuccessBlock = (result: T) -> Void | |
public typealias PromiseFailureBlock = (error: NSError?) -> Void | |
public typealias PromiseAlwaysBlock = () -> Void | |
private(set) var successBlocks = [PromiseSuccessBlock]() | |
private(set) var failureBlocks = [PromiseFailureBlock]() | |
private(set) var alwaysBlocks = [PromiseAlwaysBlock]() | |
public func success(block: PromiseSuccessBlock) -> Self { | |
successBlocks.append(block) | |
return self | |
} | |
public func failure(block: PromiseFailureBlock) -> Self { | |
failureBlocks.append(block) | |
return self | |
} | |
public func always(block: PromiseAlwaysBlock) -> Self { | |
alwaysBlocks.append(block) | |
return self | |
} | |
public func resolve(result: T) { | |
successBlocks.map { $0(result: result) } | |
alwaysBlocks.map { $0() } | |
} | |
public func reject(error: NSError?) { | |
failureBlocks.map { $0(error: error) } | |
alwaysBlocks.map { $0() } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment