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.
This commit is contained in:
parent
a22389aa4a
commit
9201908b54
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue