Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions Sources/AwaitKit/AwaitKit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,24 @@ public func await<T>(_ promise: Promise<T>) 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<T>(_ promise: Promise<T>?) 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.
Expand All @@ -83,3 +101,18 @@ public func await<T>(_ promise: Promise<T>) throws -> T {
public func await<T>(_ guarantee: Guarantee<T>) 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<T>(_ guarantee: Guarantee<T>?) throws -> T? {
if let guarantee = guarantee {
return try Queue.await.ak.await(guarantee)
}

return nil
}
10 changes: 10 additions & 0 deletions Tests/AwaitKitTests/AwaitKitAwaitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,14 @@ class AwaitKitAwaitTests: XCTestCase {

XCTAssertNil(error)
}

func testAwaitNilPromise() {
let error = try? await(nil as Promise<Void>?)
XCTAssertNil(error)
}

func testAwaitNilGuarantee() {
let error = try? await(nil as Guarantee<Void>?)
XCTAssertNil(error)
}
}