Skip to content
Permalink
Browse files

Allow promises to be completed with a `Result<Value, Error>` (#1124)

Motivation:

When dealing with `Result` types and promises it is inconvenient having to
switch over the result in order to succeed or fail a promise.

Modifications:

- Allow promises to be completed with a `Result<Value, Error>` directly.
- Added tests.

Result:

Promises are easier to fulfill with `Result` types.
  • Loading branch information...
glbrntt authored and Lukasa committed Sep 10, 2019
1 parent a22389a commit 9201908b54578aa33f1d1826a5a680aca8991843
@@ -197,6 +197,25 @@ public struct EventLoopPromise<Value> {
future.cascade(to: self)
}

/// Complete the promise with the passed in `Result<Value, Error>`.
///
/// This method is equivalent to invoking:
/// ```
/// switch result {
/// case .success(let value):
/// promise.succeed(value)
/// case .failure(let error):
/// promise.fail(error)
/// }
/// ```
///
/// - parameters:
/// - result: The result which will be used to succeed or fail this promise.
@inlinable
public func completeWith(_ result: Result<Value, Error>) {
self._resolve(value: result)
}

/// Fire the associated `EventLoopFuture` on the appropriate event loop.
///
/// This method provides the primary difference between the `EventLoopPromise` and most
@@ -74,6 +74,8 @@ extension EventLoopFutureTest {
("testAlwaysWithFailingPromise", testAlwaysWithFailingPromise),
("testPromiseCompletedWithSuccessfulFuture", testPromiseCompletedWithSuccessfulFuture),
("testPromiseCompletedWithFailedFuture", testPromiseCompletedWithFailedFuture),
("testPromiseCompletedWithSuccessfulResult", testPromiseCompletedWithSuccessfulResult),
("testPromiseCompletedWithFailedResult", testPromiseCompletedWithFailedResult),
]
}
}
@@ -1088,4 +1088,28 @@ class EventLoopFutureTest : XCTestCase {
XCTAssert(type(of: error) == EventLoopFutureTestError.self)
}
}

func testPromiseCompletedWithSuccessfulResult() throws {
let group = EmbeddedEventLoop()
let loop = group.next()

let promise = loop.makePromise(of: Void.self)

let result: Result<Void, Error> = .success(())
promise.completeWith(result)
XCTAssertNoThrow(try promise.futureResult.wait())
}

func testPromiseCompletedWithFailedResult() throws {
let group = EmbeddedEventLoop()
let loop = group.next()

let promise = loop.makePromise(of: Void.self)

let result: Result<Void, Error> = .failure(EventLoopFutureTestError.example)
promise.completeWith(result)
XCTAssertThrowsError(try promise.futureResult.wait()) { error in
XCTAssert(type(of: error) == EventLoopFutureTestError.self)
}
}
}

0 comments on commit 9201908

Please sign in to comment.
You can’t perform that action at this time.