Skip to content

Commit

Permalink
Add support for Promise races
Browse files Browse the repository at this point in the history
  • Loading branch information
EricRabil committed Sep 17, 2021
1 parent 5b6d3f3 commit 87a1e22
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
24 changes: 24 additions & 0 deletions Sources/Pwomise/Pwomise.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,36 @@ public protocol PromiseConvertible {
var asPromise: Promise<Output> { get }
}

public enum PromiseInconsistencyError: Error {
case emptyArray
}

public class Promise<Output>: CustomDebugStringConvertible {
internal typealias Pending = PendingPromise<Output, Error>
public typealias Completion = Result<Output, Error>
public typealias Resolve = (Output) -> ()
public typealias Reject = (Error) -> ()

public static func any(_ promises: [Promise<Output>]) -> Promise<Output> {
guard promises.count > 0 else {
return .failure(PromiseInconsistencyError.emptyArray)
}

let superPromise = Promise()

for promise in promises {
promise.always { completion in
guard superPromise.pending else {
return
}

superPromise.result = .resolved(completion)
}
}

return superPromise
}

public static func all(_ promises: [Promise<Output>]) -> Promise<[Output]> {
guard promises.count > 0 else {
return .success([])
Expand Down
17 changes: 16 additions & 1 deletion Tests/PwomiseTests/PwomiseTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,20 @@
@testable import Pwomise

final class PwomiseTests: XCTestCase {

func testRace() {
var fulfilled = false

Promise<Void>.any([
Promise { resolve, reject in
resolve(())
},
Promise { resolve, reject in
resolve(())
}
]).then { _ in
XCTAssert(!fulfilled, "resolved multiple times")

fulfilled = true
}
}
}

0 comments on commit 87a1e22

Please sign in to comment.