diff --git a/Sources/AwaitKit/AwaitKit.swift b/Sources/AwaitKit/AwaitKit.swift index 4902dad..562eb72 100644 --- a/Sources/AwaitKit/AwaitKit.swift +++ b/Sources/AwaitKit/AwaitKit.swift @@ -73,6 +73,24 @@ public func await(_ promise: Promise) throws -> T { return try Queue.await.ak.await(promise) } +/** + If `promise` is not `nil`, awaits that the given promise resolved and returns its value or throws an error if the promise failed. If the `promise` is `nil`, immediately returns `nil`. + + This function is intended to be used with optional chaining. + + - parameter promise: The promise to resolve. + - throws: The error produced when the promise is rejected. + - returns: The value of the promise when it is resolved, or `nil` if the passed promise is `nil`. + */ +@discardableResult +public func await(_ promise: Promise?) throws -> T? { + if let promise = promise { + return try Queue.await.ak.await(promise) + } + + return nil +} + /** Awaits that the given guarantee resolved and returns its value or throws an error if the current and target queues are the same. - parameter guarantee: The guarantee to resolve. @@ -83,3 +101,18 @@ public func await(_ promise: Promise) throws -> T { public func await(_ guarantee: Guarantee) throws -> T { return try Queue.await.ak.await(guarantee) } + +/** + If `guarantee` is not `nil`, awaits that the given guarantee resolved and returns its value or throws an error if the current and target queues are the same. If the `guarantee` is `nil`, immediately returns `nil`. + - parameter guarantee: The guarantee to resolve. + - throws: when the queues are the same. + - returns: The value of the guarantee when it is resolved, or `nil` if the passed guarantee is `nil`. + */ +@discardableResult +public func await(_ guarantee: Guarantee?) throws -> T? { + if let guarantee = guarantee { + return try Queue.await.ak.await(guarantee) + } + + return nil +} diff --git a/Tests/AwaitKitTests/AwaitKitAwaitTests.swift b/Tests/AwaitKitTests/AwaitKitAwaitTests.swift index a166564..c08cd1f 100644 --- a/Tests/AwaitKitTests/AwaitKitAwaitTests.swift +++ b/Tests/AwaitKitTests/AwaitKitAwaitTests.swift @@ -126,4 +126,14 @@ class AwaitKitAwaitTests: XCTestCase { XCTAssertNil(error) } + + func testAwaitNilPromise() { + let error = try? await(nil as Promise?) + XCTAssertNil(error) + } + + func testAwaitNilGuarantee() { + let error = try? await(nil as Guarantee?) + XCTAssertNil(error) + } }